std::async 有一个重载,它将 std::launch 策略作为第一个参数。我什么时候应该使用这个重载?有哪些不同的政策? (我认为同步和异步是两个选项)。我什么时候应该使用同步策略?这与直接运行它有何不同?
最佳答案
摘要来自 the very helpful article that Jagannath linked ,以及对可能用途的评论。
有 3 种启动策略:
-
any
: 库选择是否生成线程 a 或 not -
async
: 你明确要求产生一个线程 -
deferred
: 你明确要求生成一个线程不
因此,deferred
政策是一种获得确定性惰性评估(也称为按需调用)的方式。例如,假设您有:
void MyClass::lazy(std::future<int> const& f) {
if (this->notReady()) { return; }
if (this->stillNotReady()) { return; }
if (this->value() == 42) { return; }
this->go(f.get());
}
现在,如果计算这个整数的值是long(例如,它可能调用网络往返),那么在所有不需要它的情况下计算它有点浪费...现在我们有了这样做的工具!
void func(MyClass& mc) {
std::future<int> f = std::async(std::launch::deferred, []() {
return stoi(memcached.get("KEY"));
});
mc.lazy(f);
}
请注意,这与使用 std::function<int()>
有细微的不同 (和一个闭包),因为计算是一劳永逸的,保证后续调用 get 总是返回相同的结果。
与其他策略的区别还可以体现在您不需要该值时是否执行操作。
-
any
: 可能在另一个线程上执行(主动)或根本不执行 -
async
: 将在另一个线程上执行 -
deferred
: 将不执行
因此,deferred
为您提供更好的控制,如果调用有副作用,这一点很重要。
关于c++ - 我什么时候应该使用 std::async with sync 作为策略?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9239811/