来自非Qt线程的QThread :: getCurrentThread()

and*_*rii 8 qt multithreading

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

谢谢!

gat*_*tto 11

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();
}
Run Code Online (Sandbox Code Playgroud)

输出:

QThread(0x7fce51410fd0) 
0x10edb6000
0x10edb6000
0x10edb6000
finished
Run Code Online (Sandbox Code Playgroud)

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

data->threadId = (Qt::HANDLE)pthread_self();
if (!QCoreApplicationPrivate::theMainThread)
    QCoreApplicationPrivate::theMainThread = data->thread;
Run Code Online (Sandbox Code Playgroud)

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

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

  • 可能有什么副作用?你为什么不建议混合它们? (2认同)