Search code examples
c++c++-chronocondition-variable

Condition variable not waking up when used with a chrono::duration<float>


Setting a condition variable to wait for a duration of type chrono::duration<float> results in the condition variable not waking up, while it wakes up fine with a chrono::duration<int>.

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

using namespace std;

void int_version()
{
   mutex my_mutex;
   unique_lock<mutex> my_lock(my_mutex);
   condition_variable my_cv;

   chrono::duration<int> my_duration(5);

   // this_thread::sleep_for(my_duration);
   my_cv.wait_for(my_lock, my_duration);
   cout << "Int version finished" << endl;;
}

void float_version()
{
   mutex my_mutex;
   unique_lock<mutex> my_lock(my_mutex);
   condition_variable my_cv;

   chrono::duration<float> my_duration(5);

   // this_thread::sleep_for(my_duration);
   my_cv.wait_for(my_lock, my_duration);
   cout << "Float version finished" << endl;;
}

int main()
{
    thread float_thread(float_version);
    float_thread.detach();

    thread int_thread(int_version);
    int_thread.detach();

    this_thread::sleep_for(chrono::seconds(10));
    cout << "10 secs elapsed" << endl;
}

I can't reproduce this behaviour with just this_thread::sleep_for, in this case both versions wake up fine.

Also, sometimes, instead of not waking up, the float version will wake up instantly without waiting 5secs. I guess it could be a spurious wake-up, but I doubt it since it never happens with the int version, and from the few tests I have done, when I try to put it in a while loop to check for spurious wake-ups it seems to constantly wake-up.

So what is happening? Am I misunderstanding something obvious about chrono::duration<float>? Am I doing something wrong with my condition variables? With the threads?

Compiled on Ubuntu 16.04 with GCC 7.2 and -std=c++17 -pthread.


Solution

  • There is nothing wrong with your codes. It is a bug of libstdc++.