文章目錄
- 1、學習新的東西可以借助ai和官方文檔
-
- 1.1 會問問題
- 異步編程教程
-
- 1. std::future
- 2. std::shared_future
- 3、std::promise
- 4、4. std::packaged_task
- 5. std::async
- 6. std::future_status 和等待函數
- 綜合代碼
- 總結
1、學習新的東西可以借助ai和官方文檔
因為別人寫的有可能會寫錯或者水平不高
1.1 會問問題
eg:
這樣寫可能會講的不清晰并且會少講函數接口等
你可以這樣問
這樣就會清晰很多。
后續不懂最好是問ai,再參考官方文檔。
異步編程教程
1. std::future
std::future 是一個模板類,用于訪問異步操作的結果。它提供了一種機制來獲取異步操作(可能在另一個線程中執行)的返回值。
常用接口
get(): 獲取結果,如果結果未準備好則阻塞
valid(): 檢查 future 是否擁有共享狀態
wait(): 等待結果變為可用
wait_for(): 等待一段時間
wait_until(): 等待直到某個時間點
#include <iostream>
#include <future>
#include <thread>
#include <chrono>int calculate() {std::this_thread::sleep_for(std::chrono::seconds(2)); // 模擬耗時計算return 42;
}int main() {// 使用 async 啟動異步任務,返回 futurestd::future<int> fut = std::async(std::launch::async, calculate);std::cout << "正在計算結果..." << std::endl;// get() 會阻塞直到結果可用int result = fut.get();std::cout << "結果是: " << result << std::endl;// 再次調用 get() 會導致異常,因為共享狀態已被消費// int result2 = fut.get(); // 錯誤!return 0;
}
2. std::shared_future
std::shared_future 類似于 std::future,但可以被多次訪問(允許多個線程等待同一個結果)。
常用接口
與 std::future 類似,但可以多次調用 get()
#include <iostream>
#include <future>
#include <thread>
#include <vector>void worker(std::shared_future<int> fut) {// 每個線程都可以安全地獲取結果int result = fut.get();std::cout << "Worker got result: " << result << std::endl;
}int main() {// 創建一個 promise 對象std::promise<int> prom;// 從 promise 獲取 futurestd::future<int> fut = prom.get_future();// 將 future 轉換為 shared_futurestd::shared_future<int> shared_fut = fut.share();// 創建多個線程共享同一個結果std::vector<std::thread> threads;for (int i = 0; i < 3; ++i) {threads.emplace_back(worker, shared_fut);}// 設置 promise 的值prom.set_value(42);// 等待所有線程完成for (auto& t : threads) {t.join();}return 0;
}
3、std::promise
std::promise 是一個模板類,用于存儲一個值或異常,稍后可以通過與之關聯的 std::future 對象獲取。
常用接口
get_future(): 獲取與 promise 關聯的 future
set_value(): 設置結果值
set_exception(): 設置異常
set_value_at_thread_exit(): 在線程退出時設置值
set_exception_at_thread_exit(): 在線程退出時設置異常
#include <iostream>
#include <future>
#include <thread>
#include <stdexcept>void calculate(std::promise<int> prom) {try {// 模擬計算std::this_thread::sleep_for(std::chrono::seconds(1));int result = 42;// 設置結果值prom.set_value(result);} catch (...) {// 捕獲所有異常并存儲在 promise 中prom.set_exception(std::current_exception(