Search code examples
c++c++11stdthread

Printing std::this_thread::get_id() gives "thread::id of a non-executing thread"?


This used to work perfectly fine (and then aliens must have hacked my PC):

#include <thread>
#include <iostream>

int main()
{
    std::cout << std::this_thread::get_id() << std::endl;

    return 0;
}

and now it prints thread::id of a non-executing thread.

ideone.com prints some ID, but it's interesting what may have caused this behavior on my platform.

$ uname -a
Linux xxx 3.13.0-77-generic #121-Ubuntu SMP Wed Jan 20 10:50:42 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux

Any ideas?


EDIT: Well.. when I add

std::cout << pthread_self() << std::endl;

both lines print the same ID, but when I remove it, the result is still the same - "non-executing thread".


Solution

  • It's a side-effect of a glibc feature, fixed in https://gcc.gnu.org/bugzilla/show_bug.cgi?id=57060:

    // For the GNU C library pthread_self() is usable without linking to
    // libpthread.so but returns 0, so we cannot use it in single-threaded
    // programs, because this_thread::get_id() != thread::id{} must be true.
    

    If you explicitly link against pthreads (-pthread or -lpthread) then your program will behave as expected.

    Oddly enough, on my system, adding a call to pthread_self (before or after the call to std::this_thread::get_id() does not change behavior:

    0
    thread::id of a non-executing thread
    

    This may be an Ubuntu-specific behavior, linking pthreads automatically if pthread_self is called, but it seems a bit odd. Note that std::this_thread::get_id() calls pthread_self via a weak reference (itself via __gthread_self).