mardi 24 avril 2018

conditional_variable "spurious" awakenings

I'm having trouble understanding conditional_variable wait_for.

Sample program:

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

std::mutex m;
std::condition_variable cv;
bool ready = false;

using namespace std;

void worker_thread()
{
    std::unique_lock<std::mutex> lk(m);

    for (int i=0; i<3; i++) {
      auto remaining = chrono::milliseconds::max();

      std::cout << "Going to sleep for " << remaining.count() << endl;
      bool r = cv.wait_for(lk, remaining, [] () { return ready;});
      std::cout << "Wakey wakey " << r << endl;
    }

    std::cout << "Thread finished" << endl;
}

int main()
{
    std::thread worker(worker_thread);
    worker.join();
}

What I expect this program to do:

  • Go to sleep forever since I never set ready to true nor called cv.notify_one()

What it actually does:

Going to sleep for 9223372036854775807
Wakey wakey 0
Going to sleep for 9223372036854775807
Wakey wakey 0
Going to sleep for 9223372036854775807
Wakey wakey 0
Thread finished

Is this because of "spurious awakenings"? But I used overload (2) which says in the documentation: This overload may be used to ignore spurious awakenings.

Execute code here: https://repl.it/repls/EnchantedFatalUnderstanding

Aucun commentaire:

Enregistrer un commentaire