I am trying to print numbers from 1 to n using two threads. One for incrementing, and the other for printing. Since there is no std library Semaphore class in new c++, I am using a mutex and a conditional variable to simulate a binary semaphore to do the job. The code below does not print any values but "main is here!". I checked my code several times and could not find a solution. Am I missing something here?
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
using namespace std;
mutex m;
condition_variable cv;
int v=0;
void modify()
{
while(v<10)
{
lock_guard<mutex> lock(m);
v=v+1;
cv.notify_all();
}
}
void print()
{
while(v<10)
{
unique_lock<mutex> lock(m);
cv.wait(lock);
cout<<v<<" ";
lock.unlock();
cv.notify_all();
}
}
int main() {
thread t1(modify);
thread t2(print);
t1.join();
t2.join();
cout<<endl<<"main is here!"<<endl;
return 0;
}