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

This worked perfectly (and then the aliens must have hacked into my computer):

#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 identifier, but it is interesting what could cause 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; 

the lines print the same identifier, but when I delete it, the result remains the same - "non-execution of the stream."

+5
source share
2 answers

This is a side effect of the glibc function, recorded 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 reference pthreads ( -pthread or -lpthread ), your program will behave as expected.

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

 0 thread::id of a non-executing thread 

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

+4
source

The standard does not actually define what this_thread::get_id will return. All he says is:

Returns: an object of type thread :: id that uniquely identifies the current thread of execution. No other part of the execution should have this id and this thread of execution should always have this id . The returned object should not be compared with the default thread :: identifier.

This condition is met with your output, so everything is in order.

By the way, do not confuse thread_id returned by this_thread::get_id with the numeric thread identifier returned by std::thread::get_id() . thread_id The main use should be compared and used in associative containers, and not directly introduced or printed.

+1
source

Source: https://habr.com/ru/post/1246236/


All Articles