学习了一下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();
}