<future>和<condition_variable>的区别
std::future
和 std::condition_variable
都是C++标准库中用于处理并发编程的工具,但它们有不同的用途和工作方式。以下是对两者的详细比较和各自的使用示例。
std::future
std::future
提供了一种机制,用于访问异步操作的结果。它通常与 std::promise
或 std::async
一起使用。
- 用途:用于异步操作的结果传递和获取。
- 工作方式:一个线程可以通过
std::future
等待另一个线程完成某个任务,并获取其结果。 - 典型使用场景:一个线程执行异步操作(如计算任务、IO操作),另一个线程等待该操作的结果。
示例
#include <iostream>
#include <future>
#include <thread>
#include <chrono>
int computeValue() {
std::this_thread::sleep_for(std::chrono::seconds(2)); // 模拟耗时操作
return 42;
}
int main() {
// 使用 std::async 启动异步任务
std::future<int> fut = std::async(std::launch::async, computeValue);
std::cout << "Waiting for the result...\n";
int result = fut.get(); // 阻塞等待结果
std::cout << "Result is: " << result << std::endl;
return 0;
}
std::condition_variable
std::condition_variable
是一种同步原语,允许线程在某些条件满足前阻塞等待。通常与互斥锁(std::mutex
)一起使用。
- 用途:用于线程间的同步,确保某些条件满足时才继续执行。
- 工作方式:一个线程等待某个条件,另一个线程在条件满足时通知等待的线程。
- 典型使用场景:一个线程等待某个资源可用,另一个线程在资源准备好时通知它。
示例
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
std::mutex mtx;
std::condition_variable cv;
bool ready = false;
void print_id(int id) {
std::unique_lock<std::mutex> lck(mtx);
while (!ready) cv.wait(lck); // 等待 ready 为 true
// 当 ready 为 true 时,继续执行
std::cout << "Thread " << id << '\n';
}
void go() {
std::unique_lock<std::mutex> lck(mtx);
ready = true;
cv.notify_all(); // 通知所有等待的线程
}
int main() {
std::thread threads[10];
for (int i = 0; i < 10; ++i)
threads[i] = std::thread(print_id, i);
std::cout << "10 threads ready to race...\n";
std::this_thread::sleep_for(std::chrono::seconds(1));
go(); // 改变 ready 并通知所有线程
for (auto& th : threads) th.join();
return 0;
}
主要区别
-
功能:
std::future
用于异步任务的结果传递。std::condition_variable
用于线程间的同步。
-
使用模式:
std::future
通过std::promise
设置结果,或者通过std::async
启动异步任务,并通过future
获取结果。std::condition_variable
需要与std::mutex
一起使用,一个线程等待条件变量,另一个线程通知条件变量。
-
同步机制:
std::future
是一种高级同步机制,主要关注结果的传递和获取。std::condition_variable
是一种低级同步原语,主要关注线程间的协调。
适用场景
-
使用
std::future
的场景:- 需要在线程间传递计算结果。
- 需要启动并等待异步任务的完成。
-
使用
std::condition_variable
的场景:- 需要在某些条件满足时通知一个或多个线程继续执行。
- 需要实现复杂的线程间同步逻辑。
总结来说,std::future
和 std::condition_variable
在并发编程中各有其独特的用途和优势,选择哪一个取决于具体的应用场景和需求。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)