【问题标题】:QThread::getCurrentThread() from non-Qt thread来自非 Qt 线程的 QThread::getCurrentThread()
【发布时间】:2013-04-25 05:56:03
【问题描述】:

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

谢谢!

【问题讨论】:

  • 何不试试看?
  • 你的意思是QThread::currentThread()吗?还有一个问题:你为什么要这样做?
  • 这可能是未定义的行为。

标签: multithreading qt


【解决方案1】:

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

QThread::currentThread 创建并初始化一个 Q(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

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

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

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

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

【讨论】:

  • 可能有什么副作用?为什么不建议混合使用?
  • 反之亦然兼容吗?即使用QThreads 创建一个线程,然后使用this_thread::get_id() 获取id。
猜你喜欢
  • 1970-01-01
  • 2017-02-13
  • 2021-12-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-17
  • 1970-01-01
相关资源
最近更新 更多