简体   繁体   中英

GCC 4.9.2 / GCC 4.8.1 - std::condition_variable::wait_until(…) bug?

I have a problem with the method wait_until on c++11 conditional variables. It looks like the method return std::cv_status::no_timeout even if there are no notifications. The code below shows the problem.

There are comments in the code below illustrating the problem.

Compiler used: gcc 4.9.2 (on arch linux) gcc 4.8.1 (on ubuntu 14.04)

I am greatful for any help i can get to solve this.

Best regars, Mats

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


std::mutex m;
std::condition_variable v;

void test_wait_until(int ms)
{
    std::unique_lock<std::mutex> lock(m);

    std::cout << ms << "ms start\n";
    auto expires = std::chrono::system_clock::now() + std::chrono::milliseconds(ms);
    bool run = true;

    do
    {
        // This loop will run at 100% cpu time until
        // the timeout expires.

        auto status = v.wait_until(lock, expires);

        if(status == std::cv_status::timeout){
            std::cout << ms << "ms expired\n";
            run=false;
        }

        if(status == std::cv_status::no_timeout){
            // If the commend below is removed the
            // termial will be filled by the printout.
            // until the timeout expires.

            //std::cout << ms << "ms did not expire\n";
        }
    }while(run);
}


int main()
{
    test_wait_until(20000);
    test_wait_until( 5000);
    test_wait_until(  100);
    test_wait_until(  100);
    test_wait_until(   10);
    test_wait_until(    0);
    test_wait_until(   -10);
    test_wait_until(  -100);
    test_wait_until(  -100);
    test_wait_until( -5000);
    test_wait_until(-20000);
}

You probably need to build your executable with threading support. On Linux with gcc 4.9.2 this would go something like this:

g++ -std=c++11 test.cpp -o test -pthread

Ok the problem was: I / we were using the -lpthread option instead of the -pthread option for gcc.

The strange this is other things works rather well, but this seams to the solution.

Thank you all!

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