Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <queue>
- #include <vector>
- #include <thread>
- #include <mutex>
- #include <condition_variable>
- #define NUMBER_OF_THREADS 5
- #define MAX_QUEUE_ELEM 500
- std::mutex m;
- std::condition_variable producerMutex;
- std::condition_variable consumerMutex[NUMBER_OF_THREADS];
- std::queue<int> Q;
- static int elemCounter = 1;
- static int threadCounter = 1;
- void producer()
- {
- while (true)
- {
- // lock thread
- std::unique_lock<std::mutex> lock(m);
- while (Q.size() == MAX_QUEUE_ELEM)
- {
- std::cout << "Producer waiting" << std::endl;
- producerMutex.wait(lock);
- }
- Q.push(elemCounter++);
- // unlock thread
- lock.unlock();
- // notify next waiting consumer thread
- consumerMutex[threadCounter].notify_one();
- }
- }
- void consumer()
- {
- while (true)
- {
- //lock thread
- std::unique_lock<std::mutex> lock(m);
- while (Q.empty())
- {
- std::cout << "Consumer waiting : "<< threadCounter << std::endl;
- consumerMutex[threadCounter].wait(lock);
- }
- int val = Q.front();
- Q.pop();
- // Printing in lock to print in sequnce
- std::cout << "val: " << val << " , thread number: " << threadCounter << std::endl;
- // unloack thread
- lock.unlock();
- // Notify to next waiting thread in sequnce
- if (threadCounter == NUMBER_OF_THREADS)
- {
- // it means this is last thread so notify first thread
- threadCounter = 1;
- consumerMutex[threadCounter].notify_one();
- }
- else
- {
- consumerMutex[++threadCounter].notify_one();
- }
- }
- }
- int main()
- {
- std::thread thrds[NUMBER_OF_THREADS];
- for (int i = 0; i < NUMBER_OF_THREADS; i++)
- {
- thrds[i] = std::thread(consumer);
- }
- producer();
- for (int i = 0; i < NUMBER_OF_THREADS; i++)
- {
- thrds[i].join();
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement