在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中使用多线程的几种常见方法。根据具体的需求和场景,选择适合的方法来实现多线程功能。