9

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)
}
Gagan Singh
  • 988
  • 12
  • 22
  • 1
    possible duplicate of [Multiple workers in Swift Command Line Tool](http://stackoverflow.com/questions/28590701/multiple-workers-in-swift-command-line-tool) – Aaron Brager Feb 27 '15 at 20:32

3 Answers3

8

In addition to using dispatch_groups, you can also do the following:

yourAsyncTask(completion: {
    exit(0)
})

RunLoop.main.run()

Some resources:

jason z
  • 1,377
  • 13
  • 19
2

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.

Community
  • 1
  • 1
Gagan Singh
  • 988
  • 12
  • 22
0

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 that you can see that things are happening int he background.

Do note that this just runs all the tasks in the background. If you want to limit the number of active tasks to for example the number of CPU cores then you have to do a little more work.

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

Stefan Arentz
  • 34,311
  • 8
  • 67
  • 88