I'm trying to implement a producer/consumer class in Swift 2 using threads and NSCondition. So far I've come up with this code:
import Foundation
class ProducterConsumer {
private let numberOfProducts = 1000
private var products: [Int] = []
private var condition = NSCondition()
private func producer() {
for var i = 0; i < numberOfProducts; ++i {
condition.lock()
products.append(i)
condition.broadcast()
condition.unlock()
}
}
private func consumer(id: Int) {
while true {
condition.lock()
while products.count == 0 {
condition.wait()
}
let product = products.popLast()!
print("[\(id)] takes \(product)")
condition.unlock()
}
}
func runAndWait() {
let queue = NSOperationQueue()
for var i = 0; i < 2; ++i {
queue.addOperationWithBlock {
self.consumer(i)
}
}
queue.addOperationWithBlock {
self.producer()
}
queue.waitUntilAllOperationsAreFinished()
}
}
let pc = ProducterConsumer()
pc.runAndWait()
Basically I'm using operation queues to create 3 new threads: 1 producer that fills a shared array of Int
(from 0 to 1000) and 2 consumers that pop the values and display them.
The results show that only consumer thread #0 "works" and seems to be poping values. I can't figure out why the consumer thread #1 won't show in the console. I'm expecting a more or less 50% working times between the two consumers. What I am missing?
[0] takes 0
[0] takes 1
...
[0] takes 998
[0] takes 999
Thank you!