Im writing a swift script to be run in terminal that dispatches to the background thread a couple of operations. Without any extra effort, after all my dispatching is done, the code reaches the end of the file and quits, killing my background operations as well. What is the best way to keep the swift script alive until my background operations are finished?
The best I have come up with is the following, but I do not believe this is the best way, or even correct.
var semaphores = [dispatch_semaphore_t]()
while x {
var semaphore = dispatch_semaphore_create(0)
semaphores.append(semaphore)
dispatch_background {
//do lengthy operation
dispatch_semaphore_signal(semaphore)
}
}
for semaphore in semaphores {
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER)
}
In addition to using dispatch_groups
, you can also do the following:
yourAsyncTask(completion: {
exit(0)
})
RunLoop.main.run()
Some resources:
Thanks to Aaron Brager, who linked to Multiple workers in Swift Command Line Tool ,
which is what I used to find my answer, using dispatch_groups to solve the problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With