async
cpp现在也支持了协程
#include <chrono>
#include <iostream>
#include <thread>
#include <string>
#include <future>
#include <vector>
#include <numeric> // For std::iota
// Timer 类保持不变
class Timer
{
std::string task_name_;
std::chrono::time_point<std::chrono::steady_clock> start_;
public:
explicit Timer(std::string task_name) : task_name_(std::move(task_name))
{
start_ = std::chrono::steady_clock::now();
}
~Timer()
{
const auto end = std::chrono::steady_clock::now();
const std::chrono::duration<double> diff = end - start_;
// 使用 iostream 以保证线程安全
std::cout << task_name_ << " took " << diff.count() << "s\n";
}
};
/**
* @brief 一个独立的异步任务,模拟一些工作并返回结果。
* @param idx 任务的标识符
* @return 计算结果
*/
int DoSomething(const int idx)
{
// 模拟耗时1秒的计算
std::this_thread::sleep_for(std::chrono::seconds(1));
// 不再需要锁,因为没有共享数据写入
// 直接返回结果
return idx;
}
int main()
{
constexpr int num_tasks = 64;
// 获取硬件支持的并发线程数
const unsigned int hardware_threads = std::thread::hardware_concurrency();
std::cout << "Hardware supports " << hardware_threads << " concurrent threads." << std::endl;
std::cout << "Starting " << num_tasks << " tasks...\n";
std::vector<std::future<int>> futures;
futures.reserve(num_tasks);
std::vector<int> results;
results.reserve(num_tasks);
{
Timer t("DoSomething tasks");
// --- 阶段1: 派发所有异步任务 ---
// 这个循环会非常快地完成,因为它只是创建线程并派发任务,而不会等待它们完成。
for (int i = 0; i < num_tasks; ++i)
{
// std::async 返回 std::future<int>,因为 DoSomething 返回 int
futures.push_back(std::async(std::launch::async, DoSomething, i));
}
// --- 阶段2: 等待并收集所有结果 ---
// 这里是同步点。循环会逐个等待 future 完成。
for (auto& f : futures)
{
// f.get() 会阻塞,直到这个特定的 future 准备好。
// 然后它返回任务的结果,并我们将其存入 vector。
results.push_back(f.get());
}
} // Timer 在这里析构,打印总耗时
// 验证并打印结果 (可以排序以方便查看)
std::sort(results.begin(), results.end());
for (const int value : results)
{
std::cout << value << " ";
}
std::cout << std::endl;
return 0;
}