Using Thread for condition variable to notify a different thread

In this Program , we have used condition variable so that we can notify the other thread to run at a particular condition.

Condition variable is better than using sleep function for particular thread as it would cause lot of unnecessary computation, Also in case we add sleep for large duration it would slow down the program.

#include 
#include
#include
#include
#include
#include
using namespace std;
template
class Queue{
queue que;
int size;
std::condition_variable cond;
std::mutex mu;
public:
Queue(int size):size(size){}
static void Producer(void * args){
//using namespace std::chrono_literals;
Queue * q=(Queue *)args;
while(q->size--){
std::unique_lock lk(q->mu);
q->que.push(q->size);
lk.unlock();
q->cond.notify_one();
//std::cout<<"before:"< std::this_thread::sleep_for(std::chrono::seconds(1));
//std::cout<<"after"< }
}
static void Consumer(void *args){
Queue *q=(Queue *)args;
while(q->size>0 || !q->que.empty()){
std::unique_lock lk(q->mu);
q->cond.wait(lk,[&]{return !q->que.empty();});
std::cout<que.front()<<"n";
q->que.pop();
lk.unlock();
}
}
};
int main(){
int num;
std::cin>>num;
Queue q(num);
std::thread t2(q.Producer,(void *)&q);
std::thread t1(q.Consumer,(void *)&q);
t2.join();
t1.join();
return 0;
}

PS: please go through this video to understand the code in case of any confusion https://youtu.be/13dFggo4t_I

“Using Thread for condition variable to notify a different thread” Posted first on ” Programming on Medium “
Author: karan goel

Author: Pawan Kumar

Leave a Reply

Close Menu
%d bloggers like this:
Skip to toolbar