From 70f683b9e1ffc1c3661e68dea6a393af0b0edb0a Mon Sep 17 00:00:00 2001 From: Sidharth Guglani Date: Sun, 19 May 2019 23:29:28 -0700 Subject: [PATCH] mutex lock while accessing event subscribers vector for thread safety Summary: Using Mutex lock_guard mechanism when writing to subscribers and when accessing them in publish to make a copy Reviewed By: davidaurelio Differential Revision: D15391679 fbshipit-source-id: 16713ff28ce1762a5ca4c48c152897a92417e80b --- ReactCommon/yoga/yoga/event/event.cpp | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/ReactCommon/yoga/yoga/event/event.cpp b/ReactCommon/yoga/yoga/event/event.cpp index 167912a9f6e1f5..e2fe3588f1f96d 100644 --- a/ReactCommon/yoga/yoga/event/event.cpp +++ b/ReactCommon/yoga/yoga/event/event.cpp @@ -34,11 +34,19 @@ void Event::reset() { void Event::subscribe(std::function&& subscriber) { std::lock_guard guard(eventSubscribersMutex()); + eventSubscribers() = + std::make_shared(*eventSubscribers()); eventSubscribers()->push_back(subscriber); } void Event::publish(const YGNode& node, Type eventType, const Data& eventData) { - for (auto& subscriber : *eventSubscribers()) { + std::shared_ptr subscribers; + { + std::lock_guard guard(eventSubscribersMutex()); + subscribers = eventSubscribers(); + } + + for (auto& subscriber : *subscribers) { if (subscriber) { subscriber(node, eventType, eventData); }