2013-04-25 74 views
4

如果从non-Qt thread调用QThread::getCurrentThread(),我会得到什么?来自非Qt线程的QThread :: getCurrentThread()

谢谢!

+0

你为什么不试试看? – sashoalm 2013-04-25 07:27:12

+0

你的意思是QThread :: currentThread()?还有一个问题:你为什么要那样做? – 2013-04-25 07:28:16

+0

这可能是未定义的行为。 – sashoalm 2013-04-25 07:35:26

回答

7

QThread只是一个包装,在它使用本地线程的场景后面。

QThread::currentThread如果它还不存在,则创建并初始化一个Q(Adopted)Thread实例。

对于unix,它使用pthread s。

#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 

我看到there是Qt应用程序主线程的初始化:

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

所以可能有一些副作用。

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