#include <future> #include <iostream> #include <chrono> int main() { auto future = std::async([] { std::this_thread::sleep_for(std::chrono::seconds(2)); std::cout << "任务完成啦!" << std::endl; }); std::cout << "主线程结束" << std::endl; return 0; }你期待啥?主线程打印“主线程结束”,任务在后台睡 2 秒后打印“任务完成啦!”。但现实是:啥也没打印!为啥?因为默认策略可能是 deferred,任务被延迟到 future.get()调用时才跑,而你没调用 get(),future析构时直接把任务扔了。
int main() { auto future = std::async([] { std::this_thread::sleep_for(std::chrono::seconds(2)); std::cout << "任务完成啦!" << std::endl; }); std::cout << "主线程结束" << std::endl; future.get(); // 强制等待任务完成 return 0; }输出:
int main() { auto future = std::async(std::launch::async, [] { std::this_thread::sleep_for(std::chrono::seconds(2)); std::cout << "任务完成啦!" << std::endl; }); std::cout << "主线程结束" << std::endl; return 0; }输出:
任务完成啦!
#include <future> #include <iostream> int main() { auto future = std::async(std::launch::async, [] { throw std::runtime_error("任务出错了!"); }); future.get(); // 没抓异常,直接崩 return 0; }运行一下,程序直接挂了,抛出“任务出错了!”。
int main() { auto future = std::async(std::launch::async, [] { throw std::runtime_error("任务出错了!"); }); try { future.get(); } catch (const std::exception& e) { std::cerr << "捕获异常:" << e.what() << std::endl; } return 0; }输出:
#include <future> #include <vector> int main() { std::vector<std::future<void>> futures; for (int i = 0; i < 1000; ++i) { futures.push_back(std::async(std::launch::async, [] { std::this_thread::sleep_for(std::chrono::seconds(1)); })); } for (auto& f : futures) f.get(); return 0; }1000 个线程同时跑,CPU 和内存直接爆炸,小机器可能直接卡死。
#include <thread> #include <queue> #include <mutex> #include <condition_variable> #include <vector> std::queue<std::function<void()>> tasks; std::mutex mtx; std::condition_variable cv; bool stop = false; void worker() { while (true) { std::function<void()> task; { std::unique_lock<std::mutex> lock(mtx); cv.wait(lock, [] { return !tasks.empty() || stop; }); if (stop && tasks.empty()) return; task = std::move(tasks.front()); tasks.pop(); } task(); } } int main() { std::vector<std::thread> workers; for (int i = 0; i < 4; ++i) { // 只用 4 个线程 workers.emplace_back(worker); } for (int i = 0; i < 1000; ++i) { std::lock_guard<std::mutex> lock(mtx); tasks.push([] { std::this_thread::sleep_for(std::chrono::seconds(1)); }); cv.notify_one(); } { std::lock_guard<std::mutex> lock(mtx); stop = true; } cv.notify_all(); for (auto& w : workers) w.join(); return0; }现在只有 4 个线程循环处理 1000 个任务,资源占用可控。
#include <future> #include <mutex> int main() { std::future<void> future; { std::mutex mtx; future = std::async(std::launch::async, [&mtx] { std::lock_guard<std::mutex> lock(mtx); }); } // mtx 析构 future.get(); // 任务用已析构的 mtx,炸了 return 0; }mtx没了,任务还想锁它,行为未定义,随时崩。
int main() { auto mtx_ptr = std::make_shared<std::mutex>(); auto future = std::async(std::launch::async, [mtx_ptr] { std::lock_guard<std::mutex> lock(*mtx_ptr); }); future.get(); // mtx_ptr 活到任务结束 return 0; }shared_ptr保证 mutex活到任务结束,安全!