其实,关于线程的使用,网上资料一大堆,这里说说我的见解。本篇着重其用法,关于线程退出,线程安全等仍需学习。
先看代码,
class WriteThread : public QObject
{
Q_OBJECT
public:
explicit WriteThread(int *ptrData,QObject *parent = nullptr);
~WriteThread();
signals:
void sig_writeOver(int data);
public slots:
// moveToThread之后即位于 其他线程中,使用信号和槽
void slot_writeContent();
private:
QThread *m_thread = nullptr;
int *m_ptrData = nullptr;
};
WriteThread::WriteThread(int *ptrData, QObject *parent)
:QObject (parent),m_ptrData(ptrData)
{
qDebug() << __FUNCTION__ << QThread::currentThreadId();
m_thread = new QThread;
this->moveToThread(m_thread);
// 正确使用
connect(m_thread, &QThread::started, this, &WriteThread::slot_writeContent);
// 容易忽略
m_thread->start();
}
WriteThread::~WriteThread()
{
QMutexLocker locker(&g_shareMutex);
m_thread->quit();
m_thread->deleteLater();
if(m_thread){
m_thread = nullptr;
}
}
void WriteThread::slot_writeContent()
{
qDebug() << __FUNCTION__ << QThread::currentThreadId();
// 写 加锁
QMutexLocker locker(&g_shareMutex);
(*m_ptrData)++;
qDebug() << "write" << *m_ptrData;
}
如何使用:
int arg = 10;
WriteThread *t_ptrWriteThread = new WriteThread(&arg); // ok
WriteThread *t_ptrWriteThread_Ex = new WriteThread(&arg, ptrParent); // error
connect( , ,t_ptrWriteThread ,&WriteThread::slot_writeContent); // ok
t_ptrWriteThread->slot_writeContent(); // error
WriteThread 0x2480
slot_writeContent 0x41ec
write 1
slot_writeContent 0x2480
write 2
- 继承自QObject的子类即可使用moveToThead方法
- 不可指定对象的parent,即parent = nullptr
- 通过信号和槽进行连接,(from Qt help document )If the receiver lives in the thread that emits the signal, Qt::DirectConnection is used. Otherwise, Qt::QueuedConnection is used.
上述主线程:0x2480,通过信号和槽,工作槽即位于其他线程:0x41ec,而通过api调用槽函数,结果还是处于主线程。