【问题标题】:GUI thread detecting in the Qt libraryQt 库中的 GUI 线程检测
【发布时间】:2010-11-01 22:27:18
【问题描述】:

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

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

【问题讨论】:

    标签: c++ multithreading qt


    【解决方案1】:

    如果你的库中有 Qt,你可以请求应用程序对象的线程。应用程序对象始终存在于主 gui 线程中。

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

    【讨论】:

    • 正确:QCoreApplication::instance()->thread()。我还会检查 instance() == 0.
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-02
    • 1970-01-01
    • 1970-01-01
    • 2021-05-16
    • 1970-01-01
    相关资源
    最近更新 更多