• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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_REGISTRY_H_
6 #define MOJO_PUBLIC_CPP_BINDINGS_LIB_SYNC_HANDLE_REGISTRY_H_
7 
8 #include <unordered_map>
9 
10 #include "base/callback.h"
11 #include "base/macros.h"
12 #include "base/memory/ref_counted.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 // SyncHandleRegistry is a thread-local storage to register handles that want to
20 // be watched together.
21 //
22 // This class is not thread safe.
23 class SyncHandleRegistry : public base::RefCounted<SyncHandleRegistry> {
24  public:
25   // Returns a thread-local object.
26   static scoped_refptr<SyncHandleRegistry> current();
27 
28   using HandleCallback = base::Callback<void(MojoResult)>;
29   bool RegisterHandle(const Handle& handle,
30                       MojoHandleSignals handle_signals,
31                       const HandleCallback& callback);
32 
33   void UnregisterHandle(const Handle& handle);
34 
35   // Waits on all the registered handles and runs callbacks synchronously for
36   // those ready handles.
37   // The method:
38   //   - returns true when any element of |should_stop| is set to true;
39   //   - returns false when any error occurs.
40   bool WatchAllHandles(const bool* should_stop[], size_t count);
41 
42  private:
43   friend class base::RefCounted<SyncHandleRegistry>;
44 
45   struct HandleHasher {
operatorHandleHasher46     size_t operator()(const Handle& handle) const {
47       return std::hash<uint32_t>()(static_cast<uint32_t>(handle.value()));
48     }
49   };
50   using HandleMap = std::unordered_map<Handle, HandleCallback, HandleHasher>;
51 
52   SyncHandleRegistry();
53   ~SyncHandleRegistry();
54 
55   HandleMap handles_;
56 
57   ScopedHandle wait_set_handle_;
58 
59   base::ThreadChecker thread_checker_;
60 
61   DISALLOW_COPY_AND_ASSIGN(SyncHandleRegistry);
62 };
63 
64 }  // namespace internal
65 }  // namespace mojo
66 
67 #endif  // MOJO_PUBLIC_CPP_BINDINGS_LIB_SYNC_HANDLE_REGISTRY_H_
68