0

What I am trying to do is each thread gets to print out its 5 characters before potentially yielding to another thread. It works but it does not do what I want. THanks for help.

for (unsigned i = 0; i < _repCount; ++i) {  
    unique_lock<mutex> lck(mtx);
     cv.wait(lck, []{return !inUse; });
        inUse = true;
    for (auto c : _printMe) {
      cout << c;
      cout.flush();  
    }
    inUse = false ;  
  }
2
Contributors
1
Reply
12
Views
2 Years
Discussion Span
Last Post by Moschops
1

You seem to have made this more complicated than it should be. In the following code, so long as the mutex named mtx is shared by all threads, each thread will wait to take the mutex, output _printMe, release the mutex. Each thread will output _printMe repeatedly; repcout times. There is no guarantee that the threads will take turns :)

for (unsigned i = 0; i < _repCount; ++i)
{  
    lock_guard<mutex> lck(mtx);
    for (auto c : _printMe) 
    {
       cout << c;
       cout.flush();  
    }
}

Edited by Moschops

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.