qtC++一个类设置四个线程
时间: 2024-04-30 11:03:54 浏览: 79
mastering_qt_cpp:掌握QT C ++
在 Qt C++ 中,创建一个线程可以使用 `QThread` 类。以下是一个简单的示例,展示如何创建一个类并为其设置四个线程:
```cpp
#include <QThread>
class MyThread : public QObject
{
Q_OBJECT
public:
MyThread(QObject *parent = nullptr) : QObject(parent) {}
public slots:
void doSomeWork()
{
// Do some work...
}
};
int main(int argc, char *argv[])
{
QCoreApplication app(argc, argv);
MyThread thread1;
QThread workerThread1;
thread1.moveToThread(&workerThread1);
workerThread1.start();
MyThread thread2;
QThread workerThread2;
thread2.moveToThread(&workerThread2);
workerThread2.start();
MyThread thread3;
QThread workerThread3;
thread3.moveToThread(&workerThread3);
workerThread3.start();
MyThread thread4;
QThread workerThread4;
thread4.moveToThread(&workerThread4);
workerThread4.start();
// Connect signals to slots
QObject::connect(&workerThread1, &QThread::started, &thread1, &MyThread::doSomeWork);
QObject::connect(&workerThread2, &QThread::started, &thread2, &MyThread::doSomeWork);
QObject::connect(&workerThread3, &QThread::started, &thread3, &MyThread::doSomeWork);
QObject::connect(&workerThread4, &QThread::started, &thread4, &MyThread::doSomeWork);
return app.exec();
}
```
在这个示例中,我们创建了一个名为 `MyThread` 的类,并将其继承自 `QObject`。该类有一个名为 `doSomeWork()` 的公共槽函数,用于在单独的线程中执行一些工作。我们创建了四个 `MyThread` 实例,并为每个实例创建了一个 `QThread` 对象。然后,我们将每个 `MyThread` 实例移动到其对应的线程中,并启动线程。最后,我们将每个线程的 `started` 信号连接到其对应的 `MyThread` 实例的 `doSomeWork()` 槽函数上。
阅读全文