本文介绍了QThread::getCurrentThread() 来自非 Qt 线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果从非Qt线程调用,我将从QThread::getCurrentThread()得到什么?

What will I get from QThread::getCurrentThread(), if it is called from non-Qt thread?

谢谢!

推荐答案

QThread 只是一个包装器,在幕后使用原生线程.

QThread is just a wrapper, behind the scene it uses native threads.

QThread::currentThread 创建并初始化一个 Q(Adopted)Thread 实例(如果尚不存在).

QThread::currentThread creates and initialises a Q(Adopted)Thread instance if it doesn't exist yet.

在 unix 的情况下,它使用 pthreads.

In case of unix it uses pthreads.

#include <iostream>
#include <thread>
#include <pthread.h>

#include <QThread>
#include <QDebug>

void run() {
    QThread *thread = QThread::currentThread();

    qDebug() << thread;
    std::cout << QThread::currentThreadId() << std::endl;
    std::cout << std::this_thread::get_id() << std::endl;
    std::cout << pthread_self() << std::endl;

    thread->sleep(1);
    std::cout << "finished\n";
}

int main() {
    std::thread t1(run);
    t1.join();
}

输出:

QThread(0x7fce51410fd0)
0x10edb6000
0x10edb6000
0x10edb6000
finished

我看到那里是初始化Qt应用主线程:

I see that there is initialisation of Qt application main thread:

data->threadId = (Qt::HANDLE)pthread_self();
if (!QCoreApplicationPrivate::theMainThread)
    QCoreApplicationPrivate::theMainThread = data->thread;

所以可能会有一些副作用.

So there might be some side effects.

我建议不要将 QThread 与非 Qt 线程混合使用.

I'd advise not to mix QThread with non-Qt threads.

这篇关于QThread::getCurrentThread() 来自非 Qt 线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 18:44