From cf55873cf9a1df4cc9ca83d226bf16a62fb3d638 Mon Sep 17 00:00:00 2001 From: bilal614 Date: Mon, 26 Aug 2024 16:56:07 +0300 Subject: [PATCH] Cleanup mbgl/actor/mailbox* implementation for repetition in ensuring valid weakScheduler exists before usage (#2733) --- include/mbgl/actor/mailbox.hpp | 5 ++-- src/mbgl/actor/mailbox.cpp | 46 +++++++++++++++------------------- 2 files changed, 22 insertions(+), 29 deletions(-) diff --git a/include/mbgl/actor/mailbox.hpp b/include/mbgl/actor/mailbox.hpp index 14df53b5f..905d3eba8 100644 --- a/include/mbgl/actor/mailbox.hpp +++ b/include/mbgl/actor/mailbox.hpp @@ -3,6 +3,7 @@ #include #include #include +#include #include #include @@ -39,10 +40,8 @@ public: void push(std::unique_ptr); void receive(); - static void maybeReceive(const std::weak_ptr&); - static std::function makeClosure(std::weak_ptr); - private: + void scheduleToRecieve(const std::optional& tag = std::nullopt); enum class State : uint32_t { Idle = 0, Processing, diff --git a/src/mbgl/actor/mailbox.cpp b/src/mbgl/actor/mailbox.cpp index 85a9e1da9..63ee6aa06 100644 --- a/src/mbgl/actor/mailbox.cpp +++ b/src/mbgl/actor/mailbox.cpp @@ -38,10 +38,7 @@ void Mailbox::open(Scheduler& scheduler_) { weakScheduler = scheduler_.makeWeakPtr(); if (!queue.empty()) { - auto guard = weakScheduler.lock(); - if (weakScheduler) { - weakScheduler->schedule(makeClosure(shared_from_this())); - } + scheduleToRecieve(); } } @@ -107,11 +104,8 @@ void Mailbox::push(std::unique_ptr message) { } if (wasEmpty) { - auto guard = weakScheduler.lock(); - if (weakScheduler) { - MLN_TRACE_ZONE(schedule) - weakScheduler->schedule(schedulerTag, makeClosure(shared_from_this())); - } + MLN_TRACE_ZONE(schedule) + scheduleToRecieve(schedulerTag); } } @@ -151,25 +145,25 @@ void Mailbox::receive() { // If there are more messages in the queue and the scheduler // is still active, create a new task to handle the next one if (!wasEmpty) { - auto guard = weakScheduler.lock(); - if (weakScheduler) { - weakScheduler->schedule(makeClosure(shared_from_this())); + scheduleToRecieve(); + } +} + +void Mailbox::scheduleToRecieve(const std::optional& tag) { + auto guard = weakScheduler.lock(); + if (weakScheduler) { + std::weak_ptr mailbox = shared_from_this(); + auto setToRecieve = [mbox = std::move(mailbox)]() { + if (auto locked = mbox.lock()) { + locked->receive(); + } + }; + if (tag) { + weakScheduler->schedule(*tag, std::move(setToRecieve)); + } else { + weakScheduler->schedule(std::move(setToRecieve)); } } } -// static -void Mailbox::maybeReceive(const std::weak_ptr& mailbox) { - if (auto locked = mailbox.lock()) { - locked->receive(); - } -} - -// static -std::function Mailbox::makeClosure(std::weak_ptr mailbox) { - return [mailbox = std::move(mailbox)]() { - maybeReceive(mailbox); - }; -} - } // namespace mbgl