Skip to content

Commit

Permalink
mutex lock while accessing event subscribers vector for thread safety
Browse files Browse the repository at this point in the history
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
  • Loading branch information
SidharthGuglani-zz authored and M-i-k-e-l committed Mar 10, 2020
1 parent 32b902f commit 70f683b
Showing 1 changed file with 9 additions and 1 deletion.
10 changes: 9 additions & 1 deletion ReactCommon/yoga/yoga/event/event.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,19 @@ void Event::reset() {

void Event::subscribe(std::function<Subscriber>&& subscriber) {
std::lock_guard<std::mutex> guard(eventSubscribersMutex());
eventSubscribers() =
std::make_shared<Event::Subscribers>(*eventSubscribers());
eventSubscribers()->push_back(subscriber);
}

void Event::publish(const YGNode& node, Type eventType, const Data& eventData) {
for (auto& subscriber : *eventSubscribers()) {
std::shared_ptr<Event::Subscribers> subscribers;
{
std::lock_guard<std::mutex> guard(eventSubscribersMutex());
subscribers = eventSubscribers();
}

for (auto& subscriber : *subscribers) {
if (subscriber) {
subscriber(node, eventType, eventData);
}
Expand Down

0 comments on commit 70f683b

Please sign in to comment.