繁体   English   中英

在`std :: future`中运行循环,直到破坏 - 惯用的方式?

[英]Run loop in `std::future` until destruction - idiomatic way?

我希望成员std::future<void>连续调用循环内的函数,直到父对象被销毁。

我当前的解决方案涉及将未来包装在具有布尔标志的类中,并在销毁时将标志设置为false。

class Wrapper
{
    std::future<void> fut;
    bool wrapperAlive{true};

public:
    Wrapper() : fut{std::async(std::launch::async, [this]
    { 
        while(wrapperAlive) doSomething();
    })} { }

    ~Wrapper()
    {
        wrapperAlive = false;
    }
};

有没有更惯用的方法呢?

这是您的代码的免费数据版本:

class Wrapper {
  std::atomic<bool> wrapperAlive{true}; // construct flag first!
  std::future<void> fut;
public:
  Wrapper() :
    fut{std::async(std::launch::async, [this]
      { 
        while(wrapperAlive)
          doSomething();
      }
    )}
  {}

  ~Wrapper() {
    wrapperAlive = false;
    fut.get(); // block, so it sees wrapperAlive before it is destroyed.
  }
};

接下来我要做的就是写:

template<class F>
struct repeat_async_t {
  F f;
  // ...
};
using repeat_async = repeat_async_t<std::function<void()>>;
template<class F>
repeat_async_t<std::decay_t<F>> make_repeat_async(F&&f){
  return {std::forward<F>(f)};
}

这需要一个任务永远重复,并将其捆绑在那里,而不是将流逻辑与执行的逻辑混合。

此时,我们可能希望添加一个中止方法。

最后,忙于循环一个线程是一个很好的主意。 因此,我们将添加某种等待更多数据消费系统。

最终看起来与你的代码有很大的不同。

暂无
暂无

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

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