Add update-mutex into Observable
authorAndrii Grynenko <andrii@fb.com>
Thu, 13 Oct 2016 01:30:12 +0000 (18:30 -0700)
committerFacebook Github Bot <facebook-github-bot-bot@fb.com>
Thu, 13 Oct 2016 01:40:36 +0000 (18:40 -0700)
Reviewed By: yfeldblum

Differential Revision: D4013256

fbshipit-source-id: 771f9becfa9e7676439209dfbf4a746c110d629d

folly/experimental/observer/Observable-inl.h

index 9bd3c83d8868d36a115077a4df6ed8cc00a2177a..95dfb484bc30a284a4306060a650754efb043388 100644 (file)
@@ -40,6 +40,14 @@ class ObserverCreator<Observable, Traits>::Context {
   }
 
   void update() {
+    // This mutex ensures there's no race condition between initial update()
+    // call and update() calls from the subsciption callback.
+    //
+    // Additionally it helps avoid races between two different subscription
+    // callbacks (getting new value from observable and storing it into value_
+    // is not atomic).
+    std::lock_guard<std::mutex> lg(updateMutex_);
+
     {
       auto newValue = Traits::get(observable_);
       if (!newValue) {
@@ -69,6 +77,8 @@ class ObserverCreator<Observable, Traits>::Context {
   observer_detail::Core::WeakPtr coreWeak_;
 
   Observable observable_;
+
+  std::mutex updateMutex_;
 };
 
 template <typename Observable, typename Traits>