Producer Consumer class
class ProducerConsumer
{
//queue for producer
let producerQueue = dispatch_queue_create("com.test.producer", DISPATCH_QUEUE_SERIAL)
//queue for consumer
let consumerQueue = dispatch_queue_create("com.test.consumer", DISPATCH_QUEUE_SERIAL)
//semaphore for wait and notify
let semaphore = dispatch_semaphore_create(0)
var item = 0
func start()
{
//start consumer
startConsumer()
//start producer
startProducer()
}
func startProducer()
{
dispatch_async(producerQueue, produce)
}
func startConsumer()
{
dispatch_async(consumerQueue, consume)
}
func produce()
{
while(true)
{
self.item++
dispatch_semaphore_signal(self.semaphore)
// temp sleep time
sleep(2)
}
}
func consume()
{
while(true)
{
dispatch_semaphore_wait(self.semaphore, DISPATCH_TIME_FOREVER)
print(self.item)
}
}
}
To start the program call
let producerConsumer = ProducerConsumer()
producerConsumer.start()
No comments:
Post a Comment