2013-04-25 72 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線程。