c++ - 在不同线程中执行 future 时避免破坏对象

标签 c++ c++11 future

想象一下下面的情况:

class A {
 public:
  folly::Future<folly::Unit> fooA(std::function<void()> callback);
};

class B {
 public:
  void fooB() {
    a_->fooA([] { doSomethingCheap_(); })  /* Executed in thread 1 */
        .via(exec_.get())
        .then([] { doSomethingExpensive_(); }) /* Executed in thread 2 */
  }
 private:
  std::shared_ptr<folly::Executor> exec_;
  std::shared_ptr<A> a_;

  void doSomethingCheap_();
  void doSomethingExpensive_();
};

如果此时我们结束执行 doSomethingCheap_()对象 B b将被销毁然后我们将得到segfault .或许我们可以容纳weak_ptr<B>class A , 但是当我们想使用 class A 时,这种方法是不可扩展的不仅在 class B但也有一些class C , ...

避免它的最佳方法是什么?

最佳答案

我不熟悉愚蠢或你正在使用什么同步机制,但看起来你可以使用你捕获并传递给调用 doSomethingExpensive 的 lambda 的 Mutex-guarded bool - 这将是一个“糟糕的 -人的加入”。锁定互斥锁,然后将 bool 翻转为 true。或者,您可以使用 absl::Notification 之类的东西 [据我所知]。

#include "absl/synchronization/notification.h"

class A {
 public:
  folly::Future<folly::Unit> fooA(std::function<void()> callback);
};

class B {
 public:
  void fooB() {
    a_->fooA([] { doSomethingCheap_(); })  /* Executed in thread 1 */
        .via(exec_.get())
        .then([this] {
                  doSomethingExpensive_();
                  finished_.Notify();
               }) /* Executed in thread 2 */
    finished_.WaitForNotification();
  }
 private:
  std::shared_ptr<folly::Executor> exec_;
  std::shared_ptr<A> a_;
  absl::Notification finished_;

  void doSomethingCheap_();
  void doSomethingExpensive_();
};

最终,加入线程似乎是正确的方法,我只是不确定在愚蠢中暴露了什么。

关于c++ - 在不同线程中执行 future 时避免破坏对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46952572/

相关文章:

C++ 识别输入值 0

c++ - 为多个窗口使用全局 QNetworkCookieJar 时应用程序崩溃

c++ - 是否可以使用 std::pair 作为 std::set 的键而没有任何重复的每个元素?

rust - 如何通过 futures::Sink 发送项目列表?

c++ - Microsoft Visual C++ 未编译

c++ - 为什么 C++ 不支持变长数组?

c++11 - 使用 boost odeint 进行精确的多维积分

c++ - 我可以在任何地方阅读 C++ 2011 FDIS 吗?

java - 如果任何包占用大量时间,则使线程超时

flutter - Dart 中的批处理 future