c ++中"main"线程的id

jco*_*der 6 c++ multithreading c++11

在c ++中有没有办法获得"主"程序线程的id?

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

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

assert(std::this_thread::get_id() == std::main_thread::get_id());
Run Code Online (Sandbox Code Playgroud)

但是当然没有这样做的功能,我看不出任何方法来获取这些信息.

R. *_*des 13

你可以保存它this_thread仍然是原始线程:

std::thread::id main_thread_id;

int main() {
    main_thread_id = std::this_thread::get_id(); // gotcha!
    /* go on */
}
Run Code Online (Sandbox Code Playgroud)

  • 为什么不直接`std :: thread :: id main_thread_id = std :: this_thread :: get_id();`? (2认同)
  • 线程ID可以重复使用.只要应用程序,就不能保证任何特定的线程都会喜欢. (2认同)