OLD | NEW |
(Empty) | |
| 1 // Copyright 2017 The Chromium Authors. All rights reserved. |
| 2 // Use of this source code is governed by a BSD-style license that can be |
| 3 // found in the LICENSE file. |
| 4 |
| 5 #include "mojo/public/cpp/bindings/sync_event_watcher.h" |
| 6 |
| 7 #include "base/logging.h" |
| 8 |
| 9 namespace mojo { |
| 10 |
| 11 SyncEventWatcher::SyncEventWatcher(base::WaitableEvent* event, |
| 12 const base::Closure& callback) |
| 13 : event_(event), |
| 14 callback_(callback), |
| 15 registry_(SyncHandleRegistry::current()), |
| 16 destroyed_(new base::RefCountedData<bool>(false)) {} |
| 17 |
| 18 SyncEventWatcher::~SyncEventWatcher() { |
| 19 DCHECK(thread_checker_.CalledOnValidThread()); |
| 20 if (registered_) |
| 21 registry_->UnregisterEvent(event_); |
| 22 destroyed_->data = true; |
| 23 } |
| 24 |
| 25 void SyncEventWatcher::AllowWokenUpBySyncWatchOnSameThread() { |
| 26 DCHECK(thread_checker_.CalledOnValidThread()); |
| 27 IncrementRegisterCount(); |
| 28 } |
| 29 |
| 30 bool SyncEventWatcher::SyncWatch(const bool* should_stop) { |
| 31 DCHECK(thread_checker_.CalledOnValidThread()); |
| 32 IncrementRegisterCount(); |
| 33 if (!registered_) { |
| 34 DecrementRegisterCount(); |
| 35 return false; |
| 36 } |
| 37 |
| 38 // This object may be destroyed during the Wait() call. So we have to preserve |
| 39 // the boolean that Wait uses. |
| 40 auto destroyed = destroyed_; |
| 41 const bool* should_stop_array[] = {should_stop, &destroyed->data}; |
| 42 bool result = registry_->Wait(should_stop_array, 2); |
| 43 |
| 44 // This object has been destroyed. |
| 45 if (destroyed->data) |
| 46 return false; |
| 47 |
| 48 DecrementRegisterCount(); |
| 49 return result; |
| 50 } |
| 51 |
| 52 void SyncEventWatcher::IncrementRegisterCount() { |
| 53 register_request_count_++; |
| 54 if (!registered_) |
| 55 registered_ = registry_->RegisterEvent(event_, callback_); |
| 56 } |
| 57 |
| 58 void SyncEventWatcher::DecrementRegisterCount() { |
| 59 DCHECK_GT(register_request_count_, 0u); |
| 60 register_request_count_--; |
| 61 if (register_request_count_ == 0 && registered_) { |
| 62 registry_->UnregisterEvent(event_); |
| 63 registered_ = false; |
| 64 } |
| 65 } |
| 66 |
| 67 } // namespace mojo |
OLD | NEW |