Skip to content

Instantly share code, notes, and snippets.

@nbhasin2
Created January 20, 2015 21:53
Show Gist options
  • Save nbhasin2/735cd80298b5d47852f2 to your computer and use it in GitHub Desktop.
Save nbhasin2/735cd80298b5d47852f2 to your computer and use it in GitHub Desktop.
Multi Threading in Swift (iOS) using Dispatch Group
//Group 4 will be executed last after 1-3 are done executing
//Multi Threadin in Swift Group Dispatch Example
//Global Dispatch Queue
let dispatchGroup = dispatch_group_create()
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), {
for i in 0...3{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), {
println("\n i - \(i)")
dispatch_group_enter(dispatchGroup)
dispatch_group_async(dispatchGroup, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), {
NSThread.sleepForTimeInterval(2.0)
println("\nBlock 1\n")
dispatch_group_leave(dispatchGroup)
})
dispatch_group_enter(dispatchGroup)
dispatch_group_async(dispatchGroup, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), {
NSThread.sleepForTimeInterval(5.0)
println("\nBlock 2\n")
dispatch_group_leave(dispatchGroup)
})
dispatch_group_enter(dispatchGroup)
dispatch_group_async(dispatchGroup, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), {
NSThread.sleepForTimeInterval(1.0)
println("\nBlock 3\n")
dispatch_group_leave(dispatchGroup)
})
dispatch_group_notify(dispatchGroup, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), {
println("\nBlock 4\n")
})
});
}
});
@odvan
Copy link

odvan commented Feb 9, 2017

Swift code doesn't work as intended. Crashed.

@teronivala
Copy link

teronivala commented Feb 9, 2017

when added dispatchGroup.enter() before each
(DisplatchQueue.global(....)) - block
then ok ...
( and in main process need to wait for those to complete - example add sleep if testing in Mac there ...)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment