活动对象的返回值

8

2010年,Herb Sutter在Dr. Dobb's的文章中提倡使用活动对象而不是裸线程。

以下是C++11版本:

class Active {
public:
    typedef std::function<void()> Message;

    Active(const Active&) = delete;
    void operator=(const Active&) = delete;

    Active() : done(false) {
        thd = std::unique_ptr<std::thread>(new std::thread( [=]{ this->run(); } ) );
    }

    ~Active() {
        send( [&]{ done = true; } );
        thd->join();
    }

    void send(Message m) { mq.push_back(m); }

private:
    bool done;
    message_queue<Message> mq; // a thread-safe concurrent queue
    std::unique_ptr<std::thread> thd;

    void run() {
        while (!done) {
            Message msg = mq.pop_front();
            msg(); // execute message
        } // note: last message sets done to true
    }
};

这个类可以像这样使用:

class Backgrounder {
public:
    void save(std::string filename) { a.send( [=] {
        // ...
    } ); }

    void print(Data& data) { a.send( [=, &data] {
        // ...
    } ); }

private:
    PrivateData somePrivateStateAcrossCalls;
    Active a;
};

我希望支持具有非void返回类型的成员函数。但是我无法想出一个好的设计来实现这一点,即不使用可以容纳异构类型对象的容器(如boost :: any )。
欢迎任何想法,特别是利用C++11功能(如std :: future和std :: promise)的答案。

1
你是在询问(不受欢迎的)std::async吗? - stefan
如果我正确理解了参考文献,std::async会启动新线程或使用线程池。我想在一个单独的线程上排队任务以进行顺序执行。 - enkelwor
1
在Herb Sutter的例子中,为什么Active要持有一个std::unique_ptr<std::thread>而不是一个普通的std::thread - Quokka
1个回答

12

这需要一些工作。

首先,编写task<Sig>task<Sig>是一个std::function,只期望其参数是可移动的,而不是可复制的。

您的内部类型Messages将是task<void()>。因此,如果您愿意,您的task可以只支持nullary函数。

其次,send创建一个std::packaged_task<R> package(f);。然后从任务中获取Future,然后将package移动到您的消息队列中。(这就是为什么您需要一个移动-only的std::function,因为packaged_task只能被移动)。

然后,您将从packaged_task返回future

template<class F, class R=std::result_of_t<F const&()>>
std::future<R> send(F&& f) {
  packaged_task<R> package(std::forward<F>(f));
  auto ret = package.get_future();
  mq.push_back( std::move(package) );
  return ret;
}

客户端可以获取 std::future 并使用它来(稍后)获取回调的结果。

有趣的是,您可以按照以下方式编写一个非常简单的移动构造的零元任务:

template<class R>
struct task {
  std::packaged_task<R> state;
  template<class F>
  task( F&& f ):state(std::forward<F>(f)) {}
  R operator()() const {
    auto fut = state.get_future();
    state();
    return f.get();
  }
};

但那种方法效率极低(封装任务包含同步内容),可能需要一些清理。我觉得这很有趣,因为它使用了packaged_task来处理只能移动的std::function部分。

就我个人而言,我遇到了足够多的原因想要移动任务(其中包括这个问题),以至于我觉得一个只能移动的std::function值得编写。以下是一个这样的实现。它没有进行大量优化(可能和大多数std::function一样快),也没有调试,但设计是可靠的:

template<class Sig>
struct task;
namespace details_task {
  template<class Sig>
  struct ipimpl;
  template<class R, class...Args>
  struct ipimpl<R(Args...)> {
    virtual ~ipimpl() {}
    virtual R invoke(Args&&...args) const = 0;
  };
  template<class Sig, class F>
  struct pimpl;
  template<class R, class...Args, class F>
  struct pimpl<R(Args...), F>:ipimpl<R(Args...)> {
    F f;
    R invoke(Args&&...args) const final override {
      return f(std::forward<Args>(args)...);
    };
  };
  // void case, we don't care about what f returns:
  template<class...Args, class F>
  struct pimpl<void(Args...), F>:ipimpl<void(Args...)> {
    F f;
    template<class Fin>
    pimpl(Fin&&fin):f(std::forward<Fin>(fin)){}
    void invoke(Args&&...args) const final override {
      f(std::forward<Args>(args)...);
    };
  };
}
template<class R, class...Args>
struct task<R(Args...)> {
  std::unique_ptr< details_task::ipimpl<R(Args...)> > pimpl;
  task(task&&)=default;
  task&operator=(task&&)=default;
  task()=default;
  explicit operator bool() const { return static_cast<bool>(pimpl); }

  R operator()(Args...args) const {
    return pimpl->invoke(std::forward<Args>(args)...);
  }
  // if we can be called with the signature, use this:
  template<class F, class=std::enable_if_t<
    std::is_convertible<std::result_of_t<F const&(Args...)>,R>{}
  >>
  task(F&& f):task(std::forward<F>(f), std::is_convertible<F&,bool>{}) {}

  // the case where we are a void return type, we don't
  // care what the return type of F is, just that we can call it:
  template<class F, class R2=R, class=std::result_of_t<F const&(Args...)>,
    class=std::enable_if_t<std::is_same<R2, void>{}>
  >
  task(F&& f):task(std::forward<F>(f), std::is_convertible<F&,bool>{}) {}

  // this helps with overload resolution in some cases:
  task( R(*pf)(Args...) ):task(pf, std::true_type{}) {}
  // = nullptr support:
  task( std::nullptr_t ):task() {}

private:
  // build a pimpl from F.  All ctors get here, or to task() eventually:
  template<class F>
  task( F&& f, std::false_type /* needs a test?  No! */ ):
    pimpl( new details_task::pimpl<R(Args...), std::decay_t<F>>{ std::forward<F>(f) } )
  {}
  // cast incoming to bool, if it works, construct, otherwise
  // we should be empty:
  // move-constructs, because we need to run-time dispatch between two ctors.
  // if we pass the test, dispatch to task(?, false_type) (no test needed)
  // if we fail the test, dispatch to task() (empty task).
  template<class F>
  task( F&& f, std::true_type /* needs a test?  Yes! */ ):
    task( f?task( std::forward<F>(f), std::false_type{} ):task() )
  {}
};

实际示例

这是一个库类可移动任务对象的初步草图。它还使用了一些C++14的特性(如std::blah_t别名)——如果您使用的是仅支持C++11的编译器,请用typename std::enable_if<???>::type替换std::enable_if_t<???>

请注意,void返回类型技巧含有一些稍微可疑的模板重载技巧。(从规范的措辞来说,这是可以争论的合法性问题,但每个C++11编译器都会接受它,如果不合法,很可能会成为合法的问题)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接