简体   繁体   中英

Synchronizing with threads

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 ;  
  }

Threads run concurrently and when they yield, it's only advisory. What you're trying to do just doesn't make any sense the way threads work.

It's like if you have two people typing on computers and you say you want the first person to type ten characters before yielding to the second. Well, that's fine, but the second person doesn't have to wait for the first person to "yield", since they're not competing for the same resources.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM