qt中的多线程和槽函数

学习了一下moveToThread的写法,不需要像继承QThread方法那样在slots和run()之间加mutex,还是很方便的。下面是qt官网推荐的多线程的写法:
在这里插入图片描述

基本的写法如下:

class MyController : public QObject {

public:
	MyController() {
		thread = new QThread;
		executor = new MyExecutor;
		executor->moveToThread(thread);
		
		// controller运行在主线程中,executor运行在子线程中
		// executor的初始化都放在executor->init()槽函数中,用thread->started()信号触发
		connect(thread, SIGNAL(started()), executor, SLOT(init()), Qt::QueuedConnection);
		// 所用controller和executor的通信通过信号和槽函数进行,注意不同类型connection的应用
		connect(this, SIGNAL(start()), executor, SLOT(run()), Qt::QueuedConnection);
		connect(executor, SIGNAL(dataready()), executor, SLOT(readdata()), Qt::BlockingQueuedConnection);
		// 如果controller中的信号用BlockingQueueConnection方式连接了executor中的槽函数,
		// 在thread->start()之前emit这个信号会导致程序卡死,因为thread开始之前executor中
		// 的槽函数是不可能执行的...不要问我是怎么想到这个的
		// connect(this, SIGNAL(setConfig()), executor, SLOT(config()), Qt::BlockingQueuedConnection);
		thread->start();
	}

private:
	QThread * thread; 
	MyExecutor * executor;  	// thread线程中要管理的对象

signals:
	void start();
}
  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值