Created
July 29, 2018 12:52
-
-
Save boraseoksoon/288b927202b68351df4946a16c1f663f to your computer and use it in GitHub Desktop.
how to sync control dispatch Async snippet
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
| //: Playground - noun: a place where people can play | |
| import UIKit | |
| var str = "Hello, playground" | |
| import Foundation | |
| func test(timeout: Double) { | |
| let queue = DispatchQueue(label: "test", attributes: .concurrent) | |
| let group = DispatchGroup() | |
| var stop = false | |
| let delay = timeout | |
| queue.async(group: group) { | |
| var str = [String]() | |
| var i = 0 | |
| while i < 1000 && !stop{ | |
| str.append(String(i)) | |
| i += 1 | |
| } | |
| print(1, "did", i, "iterations") | |
| } | |
| group.wait(wallTimeout: .now() + delay) | |
| queue.async(group: group) { | |
| var str = [String]() | |
| var i = 0 | |
| while i < 2000 && !stop{ | |
| str.append(String(i)) | |
| i += 1 | |
| } | |
| print(2, "did", i, "iterations") | |
| } | |
| group.wait(wallTimeout: .now() + delay) | |
| queue.async(group: group) { | |
| var str = [String]() | |
| var i = 0 | |
| while i < 100 && !stop{ | |
| str.append(String(i)) | |
| i += 1 | |
| } | |
| print(3, "did", i, "iterations") | |
| } | |
| group.wait(wallTimeout: .now() + delay) | |
| queue.async(group: group) { | |
| var str = [String]() | |
| var i = 0 | |
| while i < 200 && !stop{ | |
| str.append(String(i)) | |
| i += 1 | |
| } | |
| print(4, "did", i, "iterations") | |
| } | |
| group.wait(wallTimeout: .now() + delay) | |
| stop = true | |
| queue.sync(flags: .barrier) {} // to be sure there are no more jobs in my queue | |
| } | |
| test(timeout: 25.0) | |
| test(timeout: 1.0) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment