Qt库中的GUI线程检测

时间:2022-02-12 01:02:49

I need to know in the context of which thread my function is running, is it main GUI thread or some worker thread.

我需要知道我的函数运行在哪个线程的上下文中,是主GUI线程还是某个工作线程。

I can't use a simple solution to store QThread pointer in the main function and compare it to QThread::currentThread() because I'm writing a library and I do not have access to the main function. I can of course create InitMyLibary() function and require library user to call it in the context of the GUI thread but I'm really against this.

我不能使用一个简单的解决方案将QThread指针存储在main函数中并将其与QThread :: currentThread()进行比较,因为我正在编写一个库而我无法访问main函数。我当然可以创建InitMyLibary()函数并要求库用户在GUI线程的上下文中调用它,但我真的反对这一点。

1 个解决方案

#1


24  

If you have Qt in the lib you can ask for the thread of the application object. The application object is alway living in the main gui thread.

如果你在lib中有Qt,你可以请求应用程序对象的线程。应用程序对象总是存在于主要的gui线程中。

void fooWorker()
{
    const bool isGuiThread = 
        QThread::currentThread() == QCoreApplication::instance()->thread();

}

#1


24  

If you have Qt in the lib you can ask for the thread of the application object. The application object is alway living in the main gui thread.

如果你在lib中有Qt,你可以请求应用程序对象的线程。应用程序对象总是存在于主要的gui线程中。

void fooWorker()
{
    const bool isGuiThread = 
        QThread::currentThread() == QCoreApplication::instance()->thread();

}