Waiting for asynchronous calls in a fast script

Im writing a quick script to run in a terminal that sends a couple of operations to the background thread. Without any extra effort, after completing my upload, the code reaches the end of the file and exits, also killing my background operations. What is the best way to keep a quick script until my background operations are complete?

The best I came up with is the following, but I don't think this is the best way or even the right one.

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) } 
+7
source share
3 answers

Thanks to Aaron Brager, who is associated with Multiple Employees in the Swift Command Line Tool ,

which I used to find the answer using dispatch_groups to solve the problem.

+2
source

How about something like this:

 func runThingsInTheBackground() { var semaphores = [dispatch_semaphore_t]() for delay in [2, 3, 10, 7] { var semaphore = dispatch_semaphore_create(0) semaphores.append(semaphore) dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) { sleep(UInt32(delay)) println("Task took \(delay) seconds") dispatch_semaphore_signal(semaphore) } } for semaphore in semaphores { dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER) } } 

This is very similar to what you have. My work "queue" is an array of seconds to sleep, so you can see that everything is happening in the background.

Note that this just runs all the tasks in the background. If you want to limit the number of active tasks, for example, the number of CPU cores, you need to do a little more work.

Not sure if this is what you were looking for, let me know.

0
source

Besides using dispatch_groups you can also do the following:

 yourAsyncTask(completion: { exit(0) }) RunLoop.main.run() 

Some resources:

0
source

Source: https://habr.com/ru/post/1214345/


All Articles