【问题标题】:Return values for active objects活动对象的返回值
【发布时间】:2015-06-15 20:05:59
【问题描述】:

早在 2010 年,Herb Sutter 就在 Dobb 博士的 article 中提倡使用活动对象而不是裸线。

这是一个 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::futurestd::promise)的答案。

【问题讨论】:

  • 你要的是(不受欢迎的)std::async 吗?
  • 如果我没看错,std::async 会启动新线程或使用线程池。我想在单个线程上对任务进行排队以便顺序执行。
  • 在 Herb Sutter 的例子中,Active 持有 std::unique_ptr&lt;std::thread&gt; 而不是普通的 std::thread 背后的基本原理是什么?

标签: c++ c++11 move-semantics active-objects


【解决方案1】:

这需要一些工作。

首先,写task&lt;Sig&gt;task&lt;Sig&gt; 是一个 std::function,它只期望它的参数是可移动的,而不是可复制的。

您的内部类型Messages 将是task&lt;void()&gt;。所以你可以偷懒,让你的task 只支持你喜欢的空函数。

其次,发送创建一个std::packaged_task&lt;R&gt; package(f);。然后它从任务中获取未来,然后将package 移动到您的消息队列中。 (这就是为什么你需要一个只能移动的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() )
  {}
};

live example

是库级仅移动任务对象的第一个草图。它还使用了一些 C++14 的东西(std::blah_t 别名)——如果您是仅 C++11 的编译器,请将 std::enable_if_t&lt;???&gt; 替换为 typename std::enable_if&lt;???&gt;::type

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    • 2020-05-05
    • 1970-01-01
    • 2019-07-01
    • 2017-10-15
    • 1970-01-01
    相关资源
    最近更新 更多