这过去工作得很好(然后外星人一定入侵了我的电脑):
#include <thread>
#include <iostream>
int main()
{
std::cout << std::this_thread::get_id() << std::endl;
return 0;
}
现在它打印CCD_ 1。
ideone.com打印了一些ID,但有趣的是,是什么导致了我的平台上出现这种行为。
$ 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
有什么想法吗?
编辑:嗯。。当我添加时
std::cout << pthread_self() << std::endl;
两行都打印相同的ID,但当我删除它时,结果仍然相同——"非执行线程"。
这是glibc功能的副作用,在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.
如果显式链接pthreads(-pthread
或-lpthread
),那么您的程序将按预期运行。
奇怪的是,在我的系统上,添加对pthread_self
的调用(在调用std::this_thread::get_id()
之前或之后)不会改变行为:
0
thread::id of a non-executing thread
这可能是Ubuntu特有的行为,如果调用pthread_self
,就会自动链接pthreads,但这似乎有点奇怪。注意,std::this_thread::get_id()
通过弱引用(自身通过__gthread_self
)调用pthread_self
。
Standard实际上并没有定义thread::id of a non-executing thread
0将返回什么。它只说:
返回:thread::id类型的对象,唯一标识当前执行线程。任何其他执行线程这个id和这个执行线程将始终具有这个id。这个返回的对象不应与默认构造的对象相比较线程::id。
您的输出满足此条件,因此一切正常。
顺便说一下,不要将this_thread::get_id
返回的thread_id
与std::thread::get_id()
返回的数字线程id混淆。thread_id
的主要用途是在关联容器中进行比较和使用,而不是直接内省或打印。