目录
qt c++ QThread 获取线程id
#include <QCoreApplication>
#include <QDebug>
#include <QThread>
class MyThread : public QThread {
Q_OBJECT
public:
MyThread(QObject *parent = nullptr) : QThread(parent) {
// 这将在主线程中执行,因为构造函数是在主线程中调用的
qDebug() << "Constructor called from thread:" << QThread::currentThread();
initialize();
}
void initialize() {
// 这个函数也是在主线程中执行的
qDebug() << "Initialize called from thread:" << QThread::currentThread();
}
protected:
void run() override {
// 这将在子线程中执行,因为 run() 方法是在调用 start() 后在子线程中运行的
qDebug() << "Run called from thread:" << QThread::currentThread();
doWork();
}
void doWork() {
// 这个函数也是在子线程中执行的
qDebug() << "DoWork called from thread:" << QThread::currentThread();
}
};
int main(int argc, char *argv[]) {
QCoreApplication app(argc, argv);
MyThread thread;
thread.start();
return app.exec();
}
#include "main.moc"
版权声明:版权没有,转载随意 https://blog.youkuaiyun.com/MAOZEXIJR/article/details/80983337
一、QThread
1、继承QObject
# -*- coding: utf-8 -*-
from PyQt5.QtCore import *
class MyWorker(QObject):
def __init__(self):
super(MyWorker, self).__init__()
def doWork(self):
# do something
pass
if __name__ == '__main__':
t = QThread()
w = MyWorker()
w.moveToThread(t)
t.start()
2、继承QThread
# -*- coding: utf-8 -*-
from PyQt5.QtCore import *
class MyThread(QThread):
def __init__(self):
super(MyThread, self).__init__()
def run(self):
# do something
pass
if __name__ == '__main__':
t = MyThread()
t.start()
二、QRunnable
# -*- coding: utf-8 -*-
from PyQt5.QtCore import *
class MyTask(QRunnable):
def __init__(self):
super(MyTask, self).__init__()
def run(self):
# do something
pass
if __name__ == '__main__':
t = MyTask()
pool = QThreadPool.globalInstance()
pool.start(t)
三、QtConcurrent
本处详细查看《QtConcurrent详解》
def fun(param):
# do something
pass
if __name__ == '__main__':
p1 = '..'
p2 = '?'
pool = QThreadPool()
f1 = QtConcurrent.run( &pool, fun, p1)
f2 = QtConcurrent.run( &pool, fun, p2)
f1.waitForFinished()
f2.waitForFinished()