简体   繁体   English

什么时候应该使用std :: async同步作为策略?

[英]When should I use std::async with sync as policy?

std::async has an overload which takes a std::launch policy as the first argument. std :: async有一个重载,它将std :: launch策略作为第一个参数。 When should I use this overload? 我什么时候应该使用这个过载? what are the different policies available? 有哪些不同的政策? (I think sync and async are the two options). (我认为同步和异步是两个选项)。 When should I use the sync policy? 我应该何时使用同步政策? How is that different from directly running it? 与直接运行有什么不同?

Summary from the very helpful article that Jagannath linked , and comments on the possible uses. Jagannath链接的非常有用的文章摘要,以及对可能用途的评论。

There are 3 launch policies: 有3个启动政策:

  • any : the library chooses whether to spawn a thread a or not any :库选择是否生成线程a
  • async : you explicitly ask for a thread to be spawned async :你明确要求生成一个线程
  • deferred : you explicitly ask for a thread not to be spawned deferred :您明确要求生成线程

Therefore, the deferred policy is a way to get deterministic lazy evaluation (also known as call by need). 因此, deferred策略是一种获得确定性惰性评估的方法 (也称为需要调用)。 For example, suppose that you have: 例如,假设您有:

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());
}

Now, if computing the value of this integer is long (for example, it may invoke a network roundtrip), then it's kinda wasteful to compute it in all the cases that do not really require it... and now we've got the tool to do so! 现在,如果计算这个整数的值很 (例如,它可能调用网络往返),那么在所有并不真正需要它的情况下计算它有点浪费...现在我们已经得到了这样做的工具!

void func(MyClass& mc) {
  std::future<int> f = std::async(std::launch::deferred, []() {
                         return stoi(memcached.get("KEY"));
                       });

  mc.lazy(f);
}

Note that this is subtly different from using a std::function<int()> (and a closure), because the computation is done once and for all , guaranteeing that subsequent calls to get always return the same result. 请注意,这与使用std::function<int()> (和闭包) 略有不同 ,因为计算是一劳永逸地完成的,保证后续的get调用始终返回相同的结果。

The difference with the other policies can also be expressed in term of whether the operation is performed when you do not need the value . 与其他策略的不同之处还可以表示是否在不需要该值时执行操作。

  • any : might be performed on another thread (proactively) or not performed at all any :可能在另一个线程上执行(主动)或根本不执行
  • async : will be performed on another thread async :将在另一个线程上执行
  • deferred : will not be performed deferred不会执行

Therefore, deferred gives you better control, which is important if the call has a side effect. 因此, deferred为您提供更好的控制,这在呼叫具有副作用时非常重要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM