简体   繁体   English

条件std :: future和std :: async

[英]Conditional std::future and std::async

I need to do conditional behavior. 我需要做条件行为。

std::future<int> f = pointer ? std::async(&Class::method, ptr) : 0;

// ... Some code

x = f.get();

So I would like to assign to x result async result of ptr->method() call or 0 if ptr is a nullptr . 所以我想将ptr->method()调用的x结果异步结果分配给x,如果ptrnullptr ,则分配为0。

Is the code above ok? 上面的代码可以吗? Can I do anything like that (assign 'int' to 'std::futture'? Or maybe there is a better solution? 我可以这样做吗(将'int'分配给'std :: futture'?或者也许有更好的解决方案?

std::future have no conversion constructor so your code is not valid (as you would have noticed if you actually tried to compile the code). std::future没有转换构造函数,因此您的代码无效(如您实际上已尝试编译代码那样,您会注意到)。

What you can do is use a default-constructed future, and then check if it's valid before you use the future. 您可以使用默认构造的Future,然后在使用Future之前检查其是否有效

You can load a value into the future without using a thread like this: 您可以在不使用如下线程的情况下将值加载到将来:

std::future<int> f;

if ( pointer )
    f = std::async(&Class::method, ptr);
else
{
    std::promise<int> p;
    p.set_value(0);
    f = p.get_future();
}

// ... Some code
x = f.get();

But a simpler way to achieve the same goal would be: 但是,实现相同目标的一种更简单的方法是:

std::future<int> f;

if ( pointer )
    f = std::async(&Class::method, ptr);

// ... Some code
x = f.valid() ? f.get() : 0;

You may return also a std::future for your other case (using different policy): 您还可以为其他情况返回std::future (使用其他策略):

std::future<int> f = pointer
    ? std::async(&Class::method, ptr)
    : std::async(std::launch::deferred, [](){ return 0;});

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

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