简体   繁体   English

c ++中“main”线程的id

[英]id of “main” thread in c++

Is there a way in c++ to get the id of the "main" program thread? 在c ++中有没有办法获得“主”程序线程的id?

I see that std::this_thread::get_id() gets the id of the currently executing thread but I need the id of the main , original program thread. 我看到std::this_thread::get_id()获取当前正在执行的线程的id,但我需要main原始程序线程的id。 I don't see any function to get this. 我没有看到任何功能来获得这个。

The reason is that I have some non thread safe internal functions that must only be called on the original thread of the application so to be safe I want to do :- 原因是我有一些非线程安全的内部函数,只能在应用程序的原始线程上调用,所以为了安全我想做: -

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

But there of course isn't a function to do that, and I can't see any way to get that information. 但是当然没有这样做的功能,我看不出任何方法来获取这些信息。

You could save it while this_thread is still the original thread: 你可以保存它,而this_thread仍然是原始线程:

std::thread::id main_thread_id;

int main() {
    main_thread_id = std::this_thread::get_id(); // gotcha!
    /* go on */
}

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. 你可以找到一些解决方案,但我只是反思...当启动新线程时,只需将主线程的id提供给它们,并将其存储在其他线程的字段中。 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. 如果在整个线程的生命中不会改变,那么你很高兴,你可以通过这些句柄引用“主”线程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM