std::future 和 std::promise 是 C++11 引入的標準庫特性,用于實現線程間的異步通信和同步。它們提供了一種機制,使一個線程能夠生成一個值或異常,并讓另一個線程獲取這個值或異常。
(線程A中設置結果)
std::promise 用于設置異步操作的結果
(線程B中獲取結果)
std::future 提供了一種機制,使線程能夠等待異步操作的結果
示例:std::promise 和 std::future的使用
#include <iostream>
#include <thread>
#include <future>// 線程函數,使用 promise 設置結果
void set_promise_value(std::promise<int>& prom) {std::this_thread::sleep_for(std::chrono::seconds(2)); // 模擬耗時操作prom.set_value(42); // 設置 promise 的結果值
}int main() {// 創建 promise 對象std::promise<int> prom;// 獲取與 promise 關聯的 future 對象std::future<int> fut = prom.get_future();// 創建線程,并將 promise 傳遞給線程函數std::thread t(set_promise_value, std::ref(prom));// 在主線程中等待 future 的結果std::cout << "Waiting for result..." << std::endl;int result = fut.get(); // 獲取結果(此時會阻塞,直到 promise 設置結果)// 輸出結果std::cout << "Result: " << result << std::endl;// 等待線程結束t.join();return 0;
}
使用 std::async
std::async 提供了一個更簡單的方法來啟動異步任務并獲取其結果。下面是一個使用 std::async 的示例:
#include <iostream>
#include <future>// 異步任務函數
int async_task() {std::this_thread::sleep_for(std::chrono::seconds(2)); // 模擬耗時操作return 42;
}int main() {// 啟動異步任務std::future<int> fut = std::async(std::launch::async, async_task);// 在主線程中等待異步任務的結果std::cout << "Waiting for result..." << std::endl;int result = fut.get(); // 獲取結果(此時會阻塞,直到異步任務完成)// 輸出結果std::cout << "Result: " << result << std::endl;return 0;
}
總結
- std::future:用于獲取異步操作的結果,可以阻塞直到結果可用(eg:std::future.get()方法)。
- std::promise:用于設置異步操作的結果,通常與 std::future 一起使用。
- std::async:提供了一種簡單的方式來啟動異步任務并返回一個 std::future,用于獲取任務結果。
通過使用 std::future 和 std::promise,可以方便地在不同線程之間進行同步和數據傳遞,簡化了異步編程的復雜性。