想象一下下面的情况:
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/