0

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;
}
Andrey Nasonov
  • 2,619
  • 12
  • 26
erol yeniaras
  • 3,701
  • 2
  • 22
  • 40

1 Answers1

0

The implementation of semaphores is very simple and can be found here: C++0x has no semaphores? How to synchronize threads?

But actually you does not need it

The problem of your code is that modify function does not wait for print function. See my changes to the code:

void modify()
{
    // Fix #1: Any access to v should be done inside lock
    unique_lock<mutex> lock(m);

    while(v<10)
    {
        v=v+1;
        cv.notify_all();

        // Fix #2: wait for print function
        cv.wait(lock);
    }
}

void print()
{
    // See Fix #1
    unique_lock<mutex> lock(m);

    while(v<10)
    {
        cv.wait(lock);
        cout << v << " ";
        // Fix #3: no need to unlock here
        cv.notify_all();
    }
}
Community
  • 1
  • 1
Andrey Nasonov
  • 2,619
  • 12
  • 26
  • Thanks for the update. I implemented your changes but still nothing is printed. I use the online compiler at http://coliru.stacked-crooked.com/ with the command g++ -std=c++14 -O2 -Wall -pedantic -pthread main.cpp && ./a.out – erol yeniaras Oct 18 '15 at 23:51
  • you need to insert std::flush as in "cout << flush()" to flush buffers – Juan Dec 09 '22 at 23:20