简体   繁体   English

如何确定我们是否在主线程中运行?

[英]How to find out if we are running in main thread?

We can get the id of the main thread by calling std::this_thread::get_id() just at the start of the main function like this answer suggests .我们可以通过在main function 的开头调用std::this_thread::get_id()来获取主线程的 ID,就像这个答案所建议的那样。 We can then store this id in a global variable and compare against a call of std::this_thread::get_id() .然后我们可以将这个id存储在一个全局变量中,并与std::this_thread::get_id()的调用进行比较。

However, this forces us to change the main function. Is there a way to create a library function that does this?但是,这迫使我们更改main function。有没有办法创建一个function 来执行此操作? I was thinking about using a global variable initialized with std::this_thread::get_id() expression.我在考虑使用一个用std::this_thread::get_id()表达式初始化的全局变量。 Since global variables (variables with static duration) are initialized relatively early it is unlikely (but not impossible, see: deferred dynamic initialization ) that threads are spawned before these variables are initialized.由于全局变量(持续时间为 static 的变量)初始化相对较早,因此不太可能(但并非不可能,请参阅: 延迟动态初始化)在初始化这些变量之前产生线程。

I could also initialize the global variable with a helper function which enumerates all threads and picks the one with the earliest creation time (based on this answer ).我还可以使用 helper function 初始化全局变量,它枚举所有线程并选择创建时间最早的线程(基于此答案)。

I am very new to multithreading so any advice or guidance is extremely welcome.我对多线程非常陌生,因此非常欢迎任何建议或指导。

There is no such thing as main thread. 没有主线程这样的东西。 There is a thread which was launched first, but all threads are first-class citizens. 有一个线程首先发布,但所有线程都是一等公民。 By tinkering with linker flags, I can easily create a program where the thread executing main() would not be the the thread launched first. 通过修改链接器标志,我可以轻松地创建一个程序,其中执行main()的线程不会是首先启动的线程。

Rethink your design. 重新思考你的设计。

EDIT 编辑

This is not a solid way of getting the main thread's ID considering what @ta.speot.is and @David Schwartz said. 考虑到@ ta.speot.is和@David Schwartz所说的,这不是获取主线程ID的可靠方法。

You could make a static variable somewhere that initializes with the current thread's ID. 您可以使用当前线程的ID初始化某个静态变量。

const std::thread::id MAIN_THREAD_ID = std::this_thread::get_id();

And then somewhere else: 然后在其他地方:

if (std::this_thread::get_id() == MAIN_THREAD_ID)
{
    std::cout << "main thread\n";
}
else
{
    std::cout << "not main thread\n";
}

If you are using MFC. You can check AfxGetMainWnd() .如果您使用的是 MFC。您可以检查AfxGetMainWnd() If it return a pWnd then you have the (MFC) main thread.如果它返回一个 pWnd,那么您就有了 (MFC) 主线程。 Disclaimer: If you have not manipulatued the m_pMainWnd Pointer.免责声明:如果您没有操纵过m_pMainWnd指针。

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

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