OLD | NEW |
| (Empty) |
1 // Copyright 2016 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 #ifndef MOJO_PUBLIC_CPP_BINDINGS_LIB_SYNC_HANDLE_WATCHER_H_ | |
6 #define MOJO_PUBLIC_CPP_BINDINGS_LIB_SYNC_HANDLE_WATCHER_H_ | |
7 | |
8 #include <unordered_map> | |
9 | |
10 #include "base/callback.h" | |
11 #include "base/macros.h" | |
12 #include "base/message_loop/message_loop.h" | |
13 #include "base/threading/thread_checker.h" | |
14 #include "mojo/public/cpp/system/core.h" | |
15 | |
16 namespace mojo { | |
17 namespace internal { | |
18 | |
19 // SyncHandleWatcher is used to support sync methods. While a sync call is | |
20 // waiting for response, we would like incoming sync method requests on the same | |
21 // thread to be able to reenter. We also would like master endpoints to continue | |
22 // dispatching messages for associated endpoints on different threads. | |
23 // Therefore, SyncHandleWatcher is used as thread-local storage to register all | |
24 // handles that need to be watched while waiting for sync call responses. | |
25 // | |
26 // This class is not thread safe. | |
27 class SyncHandleWatcher : public base::MessageLoop::DestructionObserver { | |
28 public: | |
29 // Returns a thread-local object. | |
30 static SyncHandleWatcher* current(); | |
31 | |
32 using HandleCallback = base::Callback<void(MojoResult)>; | |
33 bool RegisterHandle(const Handle& handle, | |
34 MojoHandleSignals handle_signals, | |
35 const HandleCallback& callback); | |
36 | |
37 void UnregisterHandle(const Handle& handle); | |
38 | |
39 // Waits on all the registered handles and runs callbacks synchronously for | |
40 // those ready handles. | |
41 // The method: | |
42 // - returns true when |*should_stop| is set to true; | |
43 // - returns false when either |caller_handle| is unregistered or any error | |
44 // occurs. | |
45 bool WatchAllHandles(const Handle& caller_handle, const bool* should_stop); | |
46 | |
47 private: | |
48 struct HandleHasher { | |
49 size_t operator()(const Handle& handle) const { | |
50 return std::hash<uint32_t>()(static_cast<uint32_t>(handle.value())); | |
51 } | |
52 }; | |
53 using HandleMap = std::unordered_map<Handle, HandleCallback, HandleHasher>; | |
54 | |
55 SyncHandleWatcher(); | |
56 ~SyncHandleWatcher() override; | |
57 | |
58 // base::MessageLoop::DestructionObserver implementation: | |
59 void WillDestroyCurrentMessageLoop() override; | |
60 | |
61 HandleMap handles_; | |
62 | |
63 ScopedHandle wait_set_handle_; | |
64 | |
65 base::ThreadChecker thread_checker_; | |
66 | |
67 DISALLOW_COPY_AND_ASSIGN(SyncHandleWatcher); | |
68 }; | |
69 | |
70 } // namespace internal | |
71 } // namespace mojo | |
72 | |
73 #endif // MOJO_PUBLIC_CPP_BINDINGS_LIB_SYNC_HANDLE_WATCHER_H_ | |
OLD | NEW |