返回活动对象的值

enk*_*wor 8 c++ active-objects move-semantics c++11

早在2010年,Herb Sutter 就在Dobb博士的一篇文章中提倡使用活性物体而不是裸线.

这是一个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
    }
};
Run Code Online (Sandbox Code Playgroud)

该类可以像这样使用:

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

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

private:
    PrivateData somePrivateStateAcrossCalls;
    Active a;
};
Run Code Online (Sandbox Code Playgroud)

我想支持具有非void返回类型的成员函数.但我无法想出一个很好的设计如何实现它,即不使用可以容纳异构类型的对象的容器(如boost::any).

任何想法是受欢迎的,尤其是那个答案使用C++ 11层的功能,如std::futurestd::promise.

Yak*_*ont 10

这需要一些工作.

首先,写task<Sig>. task<Sig>是一个std::function只希望它的论点是可移动的,而不是可复制的.

你的内部类型 Messages将是task<void()>.所以你可以懒惰,task如果你愿意,你可以得到唯一的支持.

第二,发送创建一个std::packaged_task<R> package(f);.然后它将使未来脱离任务,然后package进入您的消息队列.(这就是为什么你需要一个只移动std::function,因为packaged_task只能移动).

然后你future从中返回packaged_task.

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;
}
Run Code Online (Sandbox Code Playgroud)

客户可以抓住std::future并使用它来(稍后)获得回叫的结果.

有趣的是,您可以编写一个非常简单的仅移动的Nullary任务,如下所示:

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();
  }
};
Run Code Online (Sandbox Code Playgroud)

但这是非常低效的(打包的任务中有同步的东西),可能需要一些清理.我发现它很有趣,因为它使用了一个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() )
  {}
};
Run Code Online (Sandbox Code Playgroud)

实例.

是图书馆类移动任务对象的第一个草图.它还使用了一些C++ 14的东西(std::blah_t别名) - 如果你是一个只有C++ 11的编译器std::enable_if_t<???>,typename std::enable_if<???>::type则替换它.

请注意,void返回类型技巧包含一些可疑的模板重载技巧.(如果它在标准的措辞下是合法的,那么它是有争议的,但每个C++ 11编译器都会接受它,如果不是,它很可能变得合法).