Qt5 QThread线程 id,pyqt多线程4种实现方式

本文详细介绍Qt中三种多线程实现方式:QThread、QRunnable和QtConcurrent。通过示例代码展示了如何创建和使用线程,以及如何在不同线程间进行通信。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目录

qt c++ QThread 获取线程id

一、QThread

1、继承QObject

2、继承QThread

二、QRunnable

三、QtConcurrent


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()

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AI算法网奇

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值