Enzo
Enzo

Reputation: 974

Threads not running in parallel after waiting for condition variable

Please see below the example for condition_variable taken from cppreference. In this example, a bunch of threads are waiting for the variable i to become i == 1. I took the example and just added a std::this_thread::sleep_for(std::chrono::seconds(1)); instruction inside the workers to check if they were actually running in parallel. To my surprise they don't, so there must be something I am not understanding. Shouldn't all the threads start at the same time once they are notified?

If I remove all the instructions related to condition_variable, then the threads do run in parallel as expected, so I believe that my compiler (LLVM with C++11 libraries) is compiling correctly.

#include <iostream>
#include <condition_variable>
#include <thread>
#include <chrono>

std::condition_variable cv;
std::mutex cv_m; 
int i = 0;

void waits()
{
  std::unique_lock<std::mutex> lk(cv_m);
  std::cerr << "Waiting... \n";
  cv.wait(lk, []{return i == 1;});
  std::cerr << "...finished waiting. i == 1\n";
  std::this_thread::sleep_for(std::chrono::seconds(1));
  std::cerr << "...finished running.\n";
}

void signals()
{
  std::this_thread::sleep_for(std::chrono::seconds(1));
  {
    std::lock_guard<std::mutex> lk(cv_m);
    std::cerr << "Notifying...\n";
  }
  cv.notify_all();

  std::this_thread::sleep_for(std::chrono::seconds(1));

  {
    std::lock_guard<std::mutex> lk(cv_m);
    i = 1;
    std::cerr << "Notifying again...\n";
  }
  cv.notify_all();
}

int main()
{
  std::thread t1(waits), t2(waits), t3(waits), t4(signals);
  t1.join();
  t2.join();
  t3.join();
  t4.join();
}

Upvotes: 1

Views: 541

Answers (1)

user7860670
user7860670

Reputation: 37513

it looks like they are running in parallel, however only one of them will be able to lock cv_m mutex after notification and the rest will just wait further.

Upvotes: 3

Related Questions