1
0
Fork 0
forked from suyu/suyu

common: fiber: Use weak_ptr when yielding.

- Avoids a memory leak, as taking a strong reference of the fiber here causes a circular reference.
- Supersedes #6006 with a more narrow fix.
This commit is contained in:
bunnei 2021-03-05 22:10:03 -08:00
parent 4cf5b860bd
commit 68ffac250a
2 changed files with 13 additions and 8 deletions

View file

@ -116,17 +116,22 @@ void Fiber::Rewind() {
boost::context::detail::jump_fcontext(impl->rewind_context, this); boost::context::detail::jump_fcontext(impl->rewind_context, this);
} }
void Fiber::YieldTo(std::shared_ptr<Fiber> from, std::shared_ptr<Fiber> to) { void Fiber::YieldTo(std::weak_ptr<Fiber> weak_from, std::shared_ptr<Fiber> to) {
ASSERT_MSG(from != nullptr, "Yielding fiber is null!");
ASSERT_MSG(to != nullptr, "Next fiber is null!"); ASSERT_MSG(to != nullptr, "Next fiber is null!");
to->impl->guard.lock(); to->impl->guard.lock();
to->impl->previous_fiber = from; to->impl->previous_fiber = weak_from.lock();
auto transfer = boost::context::detail::jump_fcontext(to->impl->context, to.get()); auto transfer = boost::context::detail::jump_fcontext(to->impl->context, to.get());
// "from" might no longer be valid if the thread was killed
if (auto from = weak_from.lock(); from != nullptr) {
ASSERT(from->impl->previous_fiber != nullptr); ASSERT(from->impl->previous_fiber != nullptr);
from->impl->previous_fiber->impl->context = transfer.fctx; from->impl->previous_fiber->impl->context = transfer.fctx;
from->impl->previous_fiber->impl->guard.unlock(); from->impl->previous_fiber->impl->guard.unlock();
from->impl->previous_fiber.reset(); from->impl->previous_fiber.reset();
} }
}
std::shared_ptr<Fiber> Fiber::ThreadToFiber() { std::shared_ptr<Fiber> Fiber::ThreadToFiber() {
std::shared_ptr<Fiber> fiber = std::shared_ptr<Fiber>{new Fiber()}; std::shared_ptr<Fiber> fiber = std::shared_ptr<Fiber>{new Fiber()};

View file

@ -41,7 +41,7 @@ public:
/// Yields control from Fiber 'from' to Fiber 'to' /// Yields control from Fiber 'from' to Fiber 'to'
/// Fiber 'from' must be the currently running fiber. /// Fiber 'from' must be the currently running fiber.
static void YieldTo(std::shared_ptr<Fiber> from, std::shared_ptr<Fiber> to); static void YieldTo(std::weak_ptr<Fiber> weak_from, std::shared_ptr<Fiber> to);
[[nodiscard]] static std::shared_ptr<Fiber> ThreadToFiber(); [[nodiscard]] static std::shared_ptr<Fiber> ThreadToFiber();
void SetRewindPoint(std::function<void(void*)>&& rewind_func, void* rewind_param); void SetRewindPoint(std::function<void(void*)>&& rewind_func, void* rewind_param);