一、目标:做一个'可用'的最小任务系统
我们要实现一个简化版任务系统,支持:
- ✅ 提交任务(任意函数)
- ✅ 工作线程自动执行
- ✅ 无任务时阻塞等待
- ✅ 支持安全关闭
- ✅ 正确释放线程
你可以理解为:
基于 C++ 标准库构建最小可用任务系统的完整方案。核心功能包括任务提交、工作线程自动执行、无任务时阻塞等待及安全关闭。技术实现上,使用 std::mutex 保护任务队列,std::condition_variable 处理线程间协作与唤醒,std::atomic<bool> 管理全局运行状态。代码展示了如何在锁外执行任务以避免阻塞并发能力,并通过 notify_all 确保所有工作线程在关闭时能正确退出。此外,还对比了 Java 线程池的封装差异,强调了 C++ 并发编程的系统级掌控要求。
我们要实现一个简化版任务系统,支持:
你可以理解为:
线程池的前身。
我们需要三类能力:
主线程 │ ├── submit() → push 任务 → notify │ ▼ 工作线程 │ ├── wait 等待任务 ├── 取任务 ├── unlock ├── 执行 └── 循环
#include <iostream>
#include <thread>
#include <vector>
#include <queue>
#include <mutex>
#include <condition_variable>
#include <atomic>
#include <functional>
class TaskSystem {
public:
TaskSystem(size_t threadCount) : running_(true) {
for (size_t i = 0; i < threadCount; ++i) {
workers_.emplace_back([this] { this->workerLoop(); });
}
}
~TaskSystem() {
shutdown();
}
// 提交任务
void submit(std::function<void()> task) {
{
std::unique_lock<std::mutex> lock(mtx_);
tasks_.push(task);
}
cv_.notify_one();
}
// 关闭系统
void shutdown() {
running_.store(false);
cv_.notify_all();
for (auto& t : workers_) {
if (t.joinable()) {
t.join();
}
}
}
private:
void workerLoop() {
while (true) {
std::function<void()> task;
{
std::unique_lock<std::mutex> lock(mtx_);
cv_.wait(lock, [this] { return !tasks_.empty() || !running_.load(); });
if (!running_.load() && tasks_.empty()) {
return;
}
task = tasks_.front();
tasks_.pop();
}
task(); // 在锁外执行任务
}
}
private:
std::vector<std::thread> workers_;
std::queue<std::function<void()>> tasks_;
std::mutex mtx_;
std::condition_variable cv_;
std::atomic<bool> running_;
};
int main() {
TaskSystem pool(3);
for (int i = 0; i < 10; ++i) {
pool.submit([i] {
std::cout << "Task " << i << " running in thread " << std::this_thread::get_id() << std::endl;
});
}
std::this_thread::sleep_for(std::chrono::seconds(1));
pool.shutdown();
return 0;
}
输出类似:
Task 0 running in thread 1234
Task 1 running in thread 5678
...
因为:
符合 atomic 使用场景。
如果这样写:
task();
放在锁内:
原则:
锁保护资源,不保护业务逻辑
cv_.wait(lock, condition);
防止:
因为:
ExecutorService pool = Executors.newFixedThreadPool(3);
pool.submit(() -> {});
pool.shutdown();
Java 帮你封装了:
你自己写。
这就是 C++ 并发'系统级能力'的核心差异。
现在你已经具备:
谁共享数据?
mutex + RAII
condition_variable
atomic
join + shutdown
队列用 mutex 等待用 cv 状态用 atomic 生命周期用 join

微信公众号「极客日志」,在微信中扫描左侧二维码关注。展示文案:极客日志 zeeklog
使用加密算法(如AES、TripleDES、Rabbit或RC4)加密和解密文本明文。 在线工具,加密/解密文本在线工具,online
将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online
将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online
将 Markdown(GFM)转为 HTML 片段,浏览器内 marked 解析;与 HTML 转 Markdown 互为补充。 在线工具,Markdown 转 HTML在线工具,online
将 HTML 片段转为 GitHub Flavored Markdown,支持标题、列表、链接、代码块与表格等;浏览器内处理,可链接预填。 在线工具,HTML 转 Markdown在线工具,online
通过删除不必要的空白来缩小和压缩JSON。 在线工具,JSON 压缩在线工具,online