Created
January 20, 2015 21:53
Multi Threading in Swift (iOS) using Dispatch Group
This file contains hidden or 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
//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") | |
}) | |
}); | |
} | |
}); |
misbell
commented
Oct 4, 2016
for swift 3.0 as of oct 4 2016
Swift code doesn't work as intended. Crashed.
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