9

c++中有没有办法获取“主”程序线程的ID?

我看到它std::this_thread::get_id()获取了当前正在执行的线程的 id,但我需要main原始程序线程的 id。我没有看到任何功能来获得这个。

原因是我有一些非线程安全的内部函数,它们只能在应用程序的原始线程上调用,所以为了安全起见,我想做:-

assert(std::this_thread::get_id() == std::main_thread::get_id());

但是当然没有功能可以做到这一点,而且我看不到任何获取该信息的方法。

4

2 回答 2

18

You could save it while this_thread is still the original thread:

std::thread::id main_thread_id;

int main() {
    main_thread_id = std::this_thread::get_id(); // gotcha!
    /* go on */
}
于 2012-11-08T11:18:04.380 回答
3

This topic seems to be discussed quite a few times here, like in this topic:

You can find some solutions, but I'd just think the other way round... When starting the new threads, just supply the id of the main thread to them, and store that in a field in the other threads. If that is not going to change throughout the threads' life, you're good to go, you can reference the "main" thread by those handles.

于 2012-11-08T11:20:14.343 回答