C++线程编程:从基础到并行计算
1. C++ Futures的使用
在C++中使用 futures 时,为确保类型安全,需先告知C++线程的签名类型。以下是实现步骤:
1. 创建 std::packaged_task{} ,并为其提供线程函数签名。这不仅能告知API要调用的线程,还能为线程结果预留存储空间,后续可通过 std::future{} 获取。
// 示例代码
#include <iostream>
#include <future>
#include <thread>
int threadFunction() {
return 42;
}
int main() {
std::packaged_task<int()> task(threadFunction);
std::future<int> future = task.get_future();
std::thread t(std::move(task));
t.join();
int result = future.get();
std::cout << "Result: " << result << std::endl;
return 0;
}
- 通过
get_future()函数从packaged_t
超级会员免费看
订阅专栏 解锁全文
5769

被折叠的 条评论
为什么被折叠?



