std::this_thread::sleep_for() and GCC

35,869

Solution 1

Confirmed that it doesn't work here as well. (Recent GCC 4.6 snapshot).

You could do the obvious and simply define it before you include any std:: headers. A bit dirty but will work until GCC fixes it (unless this is intended behavior). The #define shouldn't break anything anyways. Either in source or -D_GLIBCXX_USE_NANOSLEEP flag to GCC.

You might want to try using -std=gnu++0x rather than -std=c++0x, since gnu++0x often pulls in stuff like this.

Solution 2

Additional information, in case it helps someone:

I do not need to define _GLIBCXX_USE_NANOSLEEP in Ubuntu 11.10, gcc 4.6.1, glibc 2.13.

But I do need to compile with -D_GLIBCXX_USE_NANOSLEEP on Gentoo, gcc 4.6.1, glibc 2.12.2.

I am not going to compile the Gentoo system for updating the glibc. At least not before the weekend ;)

Solution 3

Seems to work without the define on ubuntu 13.04 using gcc version 4.7.3

Solution 4

Need to define _GLIBCXX_USE_NANOSLEEP on top of the source code.

#define _GLIBCXX_USE_NANOSLEEP  //add it top of c++ code

OR, Compile with following commamd:

g++ a.cpp -o a -std=c++0x -D_GLIBCXX_USE_NANOSLEEP    //compile c++ code
./a       // run c++ code
Share:
35,869
Predrag
Author by

Predrag

Updated on January 17, 2020

Comments

  • Predrag
    Predrag over 4 years

    When I try to compile this simple program:

    #include<thread>
    
    void f() {
      std::this_thread::sleep_for(std::chrono::seconds(3));
    }
    
    int main() {
      std::thread t(f);
      t.join();
    }
    

    with gcc version 4.4.3 on Ubuntu 10.04 (32 bit):

    $ g++ -std=c++0x -pthread a.cpp -o a
    

    I get:

    error: ‘sleep_for’ is not a member of ‘std::this_thread’
    

    I looked in header 'thread'.
    sleep_for() is protected with _GLIBCXX_USE_NANOSLEEP

    #ifdef _GLIBCXX_USE_NANOSLEEP
    ...
    /// sleep_for
    template<typename _Rep, typename _Period>
      inline void
      sleep_for(const chrono::duration<_Rep, _Period>& __rtime)
    ...
    

    Why is _GLIBCXX_USE_NANOSLEEP not defined?
    How do I get this example to compile?


    Update 17 Sep 2012 (jogojapan): I ran into this same problem today, using GCC 4.7.1. I wonder if there is any news on how to avoid it, other than by defining _GLIBCXX_USE_NANOSLEEP. I tried using -std=gnu11, but to no avail.

    There is also an old, unresolved bug report for GCC 4.4: https://bugs.launchpad.net/ubuntu/+source/gcc-4.4/+bug/608145


    Update 19 Oct 2012 (jogojapan): The issue has now been explained and resolved by Jonathan Wakely as an anwer to this question: What is _GLIBCXX_USE_NANOSLEEP all about? This is particularly relevant for anyone who builds GCC himself instead of using a ready-made package.