10

QThread::getCurrentThread()如果它被调用,我将从中得到什么non-Qt thread

谢谢!

4

1 回答 1

12

QThread只是一个包装器,在幕后它使用本机线程。

QThread::currentThreadQ(Adopted)Thread如果实例尚不存在,则创建并初始化实例。

在 unix 的情况下,它使用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 应用程序主线程的初始化:

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

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

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

于 2013-04-25T08:36:48.320 回答