在 C++ 中,可以使用多种方式来开启异步任务,以便在程序执行过程中可以同时处理多个任务而不会阻塞主线程。以下是几种常见的方法:
- C++11 标准库中的
std::async
:std::async
是 C++11 标准库中提供的异步任务库,可以在不创建显式线程的情况下创建异步任务。它返回一个std::future
对象,用于获取异步任务的结果。例如:
#include <iostream>
#include <future>
int foo() {
// 异步任务的实现
// ...
return result;
}
int main() {
// 开启异步任务
std::future<int> future_result = std::async(std::launch::async, foo);
// 主线程继续执行其他操作
// 获取异步任务的结果
int result = future_result.get();
std::cout << "异步任务的结果: " << result << std::endl;
return 0;
}
- C++11 标准库中的
std::thread
:std::thread
是 C++11 标准库中提供的线程库,可以显式创建线程并在其中执行异步任务。例如:
#include <iostream>
#include <thread>
void foo() {
// 异步任务的实现
// ...
}
int main() {
// 创建线程并执行异步任务
std::thread t(foo);
// 主线程继续执行其他操作
// 等待线程执行完毕
t.join();
return 0;
}
- C++11 标准库中的
std::promise
和std::future
:std::promise
和std::future
是 C++11 标准库中提供的一种通信机制,可以在不创建显式线程的情况下传递异步任务的结果。例如:
#include <iostream>
#include <future>
void foo(std::promise<int>& prom) {
// 异步任务的实现
// ...
// 设置异步任务的结果
prom.set_value(result);
}
int main() {
// 创建 promise 对象和 future 对象
std::promise<int> prom;
std::future<int> future_result = prom.get_future();
// 开启异步任务
std::thread t(foo, std::ref(prom));
// 主线程继续执行其他操作
// 获取异步任务的结果
int result = future_result.get();
std::cout << "异步任务的结果: " << result << std::endl;
// 等待线程执行完毕
t.join();
return 0;
}