一、目标:做一个'可用'的最小任务系统
我们要实现一个简化版任务系统,支持:
- ✅ 提交任务(任意函数)
- ✅ 工作线程自动执行
- ✅ 无任务时阻塞等待
- ✅ 支持安全关闭
- ✅ 正确释放线程
你可以理解为:
线程池的前身。
二、设计思路(系统取向)
我们需要三类能力:
1️⃣ 资源保护(队列)
- 任务队列
- 多线程访问
- 必须用 mutex 保护
2️⃣ 线程协作(等待任务)
- 队列空 → 线程休眠
- 新任务 → 唤醒线程
- 使用 condition_variable
3️⃣ 状态控制(停止系统)
- 停止标志
- 使用 atomic
三、整体结构图
主线程 │ ├── submit() → push 任务 → notify │ ▼ 工作线程 │ ├── wait 等待任务 ├── 取任务 ├── unlock ├── 执行 └── 循环
四、完整实现(可直接运行)
1️⃣ 头文件
#include <iostream>
#include <thread>
#include <vector>
#include <queue>
#include <mutex>
#include <condition_variable>
#include <atomic>
#include <functional>
2️⃣ 任务系统类
class TaskSystem {
public:
TaskSystem(size_t threadCount) : () {
( i = ; i < threadCount; ++i) {
workers_.([] { ->(); });
}
}
~() {
();
}
{
{
;
tasks_.(task);
}
cv_.();
}
{
running_.();
cv_.();
(& t : workers_) {
(t.()) {
t.();
}
}
}
:
{
() {
std::function<()> task;
{
;
cv_.(lock, [] { !tasks_.() || !running_.(); });
(!running_.() && tasks_.()) {
;
}
task = tasks_.();
tasks_.();
}
();
}
}
:
std::vector<std::thread> workers_;
std::queue<std::function<()>> tasks_;
std::mutex mtx_;
std::condition_variable cv_;
std::atomic<> running_;
};

