体验C++的异步,有返回值的线程

#include <future>
#include <iostream>
#include <stdexcept>

/*
https://learn.microsoft.com/zh-cn/cpp/standard-library/thread-safety-in-the-cpp-standard-library?view=msvc-170
这里指出std::cout对象是线程安全的。
*/

int main() {
	/*
	C++标准指出,如果策略为 launch::async,该函数的行为就像它在新线程中调用可调用的对象一样。
	这意味着,虽然它通常会导致创建新线程,但实现可能会使用其他机制来实现等效的行为。
	https://learn.microsoft.com/zh-cn/cpp/standard-library/future-functions?view=msvc-170#async

	这里lambda表达式、函数指针就像Java的Callable,std::future就像Java的Future。
	*/
	std::future<int> future=std::async(std::launch::async,[]() {
		std::this_thread::sleep_for(std::chrono::milliseconds(500));
		std::cout<<"线程"<<std::this_thread::get_id()<<"将抛出异常\n";
		throw std::runtime_error("线程内出错");
		return 42;
		});
	std::cout<<"主线程"<<std::this_thread::get_id()<<"执行其它任务\n";
	std::this_thread::sleep_for(std::chrono::seconds(1));
	try {
		std::cout<<"主线程试图获取结果\n";
		int result=future.get();
		std::cout<<"结果:"<<result;
	}
	catch (const std::runtime_error& e) {
		std::cout<<e.what()<<'\n';
	}
}
posted @ 2026-04-07 12:20  黄铎彦  阅读(2)  评论(0)    收藏  举报