Qt 程序有一个任务队列,需要在工作线程中执行,每次任务通过startTask即可,此时任务未开始状态,同1时间最多只能开启两个任务,任务可能中途失败。任务完成100%后有限完成 未开始过的第一个任务。请给出源码
时间: 2023-06-19 09:10:53 浏览: 80
QT中,三种开启线程的方式源码
以下是一个简单的示例代码,实现了任务队列的限制和失败重试功能:
```cpp
#include <QThread>
#include <QMutex>
#include <QWaitCondition>
#include <QQueue>
class Task : public QObject
{
Q_OBJECT
public:
enum Status {
NotStarted,
Running,
Failed,
Succeeded
};
Task(QObject *parent = nullptr) : QObject(parent), m_status(NotStarted) {}
virtual void run() = 0;
Status status() const { return m_status; }
signals:
void started();
void failed();
void succeeded();
protected:
void setStatus(Status status) { m_status = status; }
private:
Status m_status;
};
class WorkerThread : public QThread
{
Q_OBJECT
public:
WorkerThread(QObject *parent = nullptr) : QThread(parent), m_runningTasks(0) {}
void addTask(Task *task) {
QMutexLocker locker(&m_mutex);
m_tasks.enqueue(task);
m_condition.wakeAll();
}
void stop() {
QMutexLocker locker(&m_mutex);
m_stop = true;
m_condition.wakeAll();
}
signals:
void taskStarted(Task *task);
void taskFailed(Task *task);
void taskSucceeded(Task *task);
protected:
void run() override {
forever {
Task *task = nullptr;
{
QMutexLocker locker(&m_mutex);
while (m_tasks.isEmpty() && !m_stop) {
m_condition.wait(&m_mutex);
}
if (m_stop) {
break;
}
if (m_runningTasks >= 2) {
continue;
}
task = m_tasks.dequeue();
m_runningTasks++;
}
emit taskStarted(task);
task->run();
if (task->status() == Task::Failed) {
emit taskFailed(task);
// Retry the task
task->run();
} else {
emit taskSucceeded(task);
}
{
QMutexLocker locker(&m_mutex);
m_runningTasks--;
if (task->status() == Task::NotStarted) {
// Complete the first unstarted task
if (!m_tasks.isEmpty()) {
task = m_tasks.dequeue();
m_runningTasks++;
locker.unlock();
emit taskStarted(task);
task->run();
if (task->status() == Task::Failed) {
emit taskFailed(task);
} else {
emit taskSucceeded(task);
}
}
}
}
}
}
private:
QMutex m_mutex;
QWaitCondition m_condition;
QQueue<Task*> m_tasks;
bool m_stop = false;
int m_runningTasks;
};
```
使用时,可以继承 `Task` 类来实现具体的任务,例如:
```cpp
class MyTask : public Task
{
public:
void run() override {
setStatus(Running);
// Do some work...
if (qrand() % 2 == 0) {
setStatus(Succeeded);
} else {
setStatus(Failed);
}
}
};
```
然后在主线程中创建一个 `WorkerThread` 对象,并调用 `addTask` 方法添加任务:
```cpp
WorkerThread *workerThread = new WorkerThread(this);
workerThread->start();
MyTask *task1 = new MyTask(this);
MyTask *task2 = new MyTask(this);
MyTask *task3 = new MyTask(this);
workerThread->addTask(task1);
workerThread->addTask(task2);
workerThread->addTask(task3);
```
最后,记得在程序退出时调用 `stop` 方法停止工作线程:
```cpp
workerThread->stop();
workerThread->wait();
```
阅读全文