Created
April 21, 2017 13:15
-
-
Save werkshy/efd95560c88676c315a411a3bb0b5f69 to your computer and use it in GitHub Desktop.
This file contains 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
#!/usr/bin/swift | |
// | |
// work.swift | |
// | |
// | |
// Created by Andy O'Neill on 4/20/17. | |
// | |
// | |
import Foundation | |
import Dispatch | |
let inputs = ["a", "b", "c", "d", "e", "f", "g", "h", "i"] | |
var finished = false | |
func work(_ input: String) -> (String) { | |
// TODO add random sleep | |
let sleepTime = arc4random_uniform(50000) | |
print("Worker '\(input)' sleeping \(sleepTime)") | |
usleep(sleepTime) | |
return input; | |
} | |
let concurrentQueue = DispatchQueue(label: "concurrentQueue", qos: .utility, attributes: .concurrent) | |
let serialQueue = DispatchQueue(label: "serialQueue") | |
let maxConcurrency = 2 | |
let semaphore = DispatchSemaphore(value: maxConcurrency) | |
let group = DispatchGroup() | |
for input in inputs { | |
serialQueue.async { | |
semaphore.wait() | |
concurrentQueue.async(group: group) { | |
let result = work(input) | |
print("Got result: " + result) | |
semaphore.signal() | |
} | |
} | |
} | |
print("Finished queuing") | |
group.wait() | |
print ("Group finished") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment