Last active
June 20, 2018 08:59
-
-
Save tkareine/dcb3599787c3fdf3e1de to your computer and use it in GitHub Desktop.
Node.js like event-loop with libdispatch and Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env xcrun swift | |
import Dispatch | |
let appQueue = dispatch_queue_create("org.tkareine.NodeLike.appQueue", DISPATCH_QUEUE_SERIAL) | |
let appGroup = dispatch_group_create() | |
func delay(delayInMS: Int, block: () -> Void) { | |
let delayInNS = Int64(delayInMS) * Int64(NSEC_PER_MSEC) | |
let scheduleAt = dispatch_time(DISPATCH_TIME_NOW, delayInNS) | |
dispatch_group_enter(appGroup) | |
dispatch_after(scheduleAt, appQueue) { | |
block() | |
dispatch_group_leave(appGroup) | |
} | |
} | |
func defer(block: () -> Void) { | |
dispatch_group_async(appGroup, appQueue, block) | |
} | |
/* | |
* The event loop. The joke is that the loop is implicit: we're using a | |
* serial queue from libdispatch and waiting for all events scheduled to | |
* it to complete. | |
*/ | |
func run(block: () -> Void) { | |
defer { | |
block() | |
} | |
dispatch_group_wait(appGroup, DISPATCH_TIME_FOREVER) | |
} | |
println("testing...") | |
var results: [Int] = [] | |
for i in 0..<10 { | |
run { | |
defer { | |
results.append(1) | |
delay(200) { | |
results.append(4) | |
delay(200) { | |
results.append(6) | |
} | |
} | |
delay(100) { | |
results.append(2) | |
defer { | |
results.append(3) | |
delay(200) { | |
results.append(5) | |
} | |
} | |
} | |
} | |
results.append(0) | |
} | |
assert(results == [0, 1, 2, 3, 4, 5, 6]) | |
results.removeAll() | |
} | |
println("ok!") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment