c++11之promise和future使用

image



int main() {

	//设置值
	{
		std::promise<string> promise;
		future<string> future = promise.get_future();

		thread t([&promise]() {
			promise.set_value("hello xiaohai");
			});

		string res = future.get();
		cout << res << endl;
		t.join();
	}
	//设置异常
	{
		std::promise<void> promise;
		future<void> future = promise.get_future();


		thread t([&promise]() {

			try {
				throw std::runtime_error("run error");
			}
			catch (...) {
				promise.set_exception(std::current_exception());
			}

			});


		try {
			future.get();  // 这里会抛出异常
		}
		catch (const std::exception& e) {
			std::cout << "Caught exception: " << e.what() << std::endl;
		}

		t.join();

	}

	//超时等待
	{


		std::promise<string> promise;
		future<string> future = promise.get_future();

		thread t([&promise]() {
			std::this_thread::sleep_for(std::chrono::seconds(3));
			promise.set_value("hello xiaohai");
			});

		auto status = future.wait_for(std::chrono::seconds(1));
		if (status == std::future_status::ready) {
			std::cout << "Got result: " << future.get() << std::endl;
		}
		else if (status == std::future_status::timeout) {
			std::cout << "Timeout! Task is still running..." << std::endl;
		}
		t.join();
			}
	//智能指针自动管理
	{

		shared_ptr<promise<float>>ptr = make_shared<promise<float>>();

		auto future = ptr->get_future();
		function<int(int)>f1 = std::bind([=](int num) ->int {
			//cout << "num="<<num << endl;
			ptr->set_value(float(num));

			return num;
			}, placeholders::_1);


		thread t(f1, 1023);

		float ret = future.get();
		cout << "ret=" << ret << endl;

		t.join();

	}

	{
		decltype(3 + 5) num1 = 5 + 3;
		cout << num1 << endl;


		shared_ptr<int>ptr = make_shared<int>(1002);
		cout << *ptr << endl;
	}

	return 0; 
}
posted @ 2025-11-20 11:26  我不是萧海哇~~~  阅读(12)  评论(0)    收藏  举报