在Qt中,有幾種方法可以使用多線程:
示例代碼:
// MyThread.h
class MyThread : public QThread
{
Q_OBJECT
public:
void run() override;
signals:
void mySignal();
};
// MyThread.cpp
void MyThread::run()
{
// 線程邏輯
emit mySignal();
}
// 使用線程
MyThread thread;
QObject::connect(&thread, SIGNAL(mySignal()), SLOT(slotFunction()));
thread.start();
示例代碼:
// MyRunnable.h
class MyRunnable : public QObject, public QRunnable
{
Q_OBJECT
public:
void run() override;
signals:
void mySignal();
};
// MyRunnable.cpp
void MyRunnable::run()
{
// 線程邏輯
emit mySignal();
}
// 使用線程
MyRunnable* runnable = new MyRunnable();
QThreadPool::globalInstance()->start(runnable);
示例代碼:
// Worker.h
class Worker : public QObject
{
Q_OBJECT
public slots:
void doWork();
signals:
void resultReady();
};
// Worker.cpp
void Worker::doWork()
{
// 線程邏輯
emit resultReady();
}
// 使用線程
QThread* thread = new QThread();
Worker* worker = new Worker();
worker->moveToThread(thread);
QObject::connect(thread, SIGNAL(started()), worker, SLOT(doWork()));
QObject::connect(worker, SIGNAL(resultReady()), thread, SLOT(quit()));
QObject::connect(worker, SIGNAL(resultReady()), worker, SLOT(deleteLater()));
QObject::connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
thread->start();
以上是Qt中使用多線程的幾種常見方法。根據具體的需求和場景,選擇適合的方法來實現多線程功能。