jeudi 26 octobre 2017

Grabbing shared_ptr before put function to execution queue

Imagine the following situation:

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_();
};

If at the time we end executing doSomethingCheap_() object B b will be destroyed then we will get segfault. Probably we can hold weak_ptr<B> in class A, but this approach is not extensible when we want to use class A not only in class B but also in some class C, ...

What is the best way avoiding it?

Aucun commentaire:

Enregistrer un commentaire