Skip to content

Instantly share code, notes, and snippets.

@boraseoksoon
Created July 29, 2018 12:52
Show Gist options
  • Select an option

  • Save boraseoksoon/288b927202b68351df4946a16c1f663f to your computer and use it in GitHub Desktop.

Select an option

Save boraseoksoon/288b927202b68351df4946a16c1f663f to your computer and use it in GitHub Desktop.
how to sync control dispatch Async snippet
//: 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