1.编译
g++ --std=c++11 -pthread demo.cpp -o demo2.示例
#include <iostream>
#include <thread>
#include <future>
#include <chrono>
#include <sstream>
// 模拟一个耗时任务
int slow_add(int a, int b) {
std::cout << "thread (slow_add) thread id:" << std::this_thread::get_id() << " running...\n";
std::this_thread::sleep_for(std::chrono::seconds(2));
return a + b;
}
// 使用 promise 设置结果
void set_promise_value(std::promise<std::string> prom, int id) {
std::this_thread::sleep_for(std::chrono::milliseconds(100 * id)); // 模拟不同处理时间
std::ostringstream oss;
oss << std::this_thread::get_id();
std::string msg = "result from thread " + std::to_string(id) + ", id: " + oss.str();
prom.set_value(msg);
}
int main() {
std::cout << "Main thread ID: " << std::this_thread::get_id() << "\n";
// 1. 使用 std::async 异步执行
std::future<int> fut_async = std::async(std::launch::async, slow_add, 3, 4);
// 2. 使用 std::async 延迟执行(同步执行)
std::future<int> fut_deferred = std::async(std::launch::deferred, slow_add, 10, 5);
// 3. 使用 std::packaged_task 封装函数,启动线程执行
std::packaged_task<int(int, int)> task(slow_add);
std::future<int> fut_task = task.get_future();
std::thread t1(std::move(task), 7, 8);
// 4. 使用 std::promise 和 future 通信(多个 promise 模拟管控多个事件)
std::promise<std::string> prom1, prom2;
std::future<std::string> fut_prom1 = prom1.get_future();
std::future<std::string> fut_prom2 = prom2.get_future();
std::thread t2(set_promise_value, std::move(prom1), 1);
std::thread t3(set_promise_value, std::move(prom2), 2);
// 获取所有结果
std::cout << "Result from async (launch::async): " << fut_async.get() << "\n";
std::cout << "Result from deferred (launch::deferred): " << fut_deferred.get() << "\n";
std::cout << "Result from packaged_task: " << fut_task.get() << "\n";
std::cout << "Promise 1: " << fut_prom1.get() << "\n";
std::cout << "Promise 2: " << fut_prom2.get() << "\n";
// Join threads
t1.join();
t2.join();
t3.join();
std::cout << "All tasks completed.\n";
return 0;
}3.输出
Main thread ID: 140015783896896
Thread (slow_add): 140015767004928 running...
Thread (slow_add): 140015758612224 running...
Result from async (launch::async): 7
Thread (slow_add): 140015783896896 running...
Result from deferred (launch::deferred): 15
Result from packaged_task: 15
Promise 1: Result from thread 1, id: 140015750219520
Promise 2: Result from thread 2, id: 140015741826816
All tasks completed.文档更新时间: 2026-03-31 15:52 作者:morninglu
