aboutsummaryrefslogtreecommitdiff
path: root/mojo/public/cpp/bindings/lib/sync_handle_registry.h
blob: d6b8c38e0ce2843b3cb57561660273a11c8bc616 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef MOJO_PUBLIC_CPP_BINDINGS_LIB_SYNC_HANDLE_REGISTRY_H_
#define MOJO_PUBLIC_CPP_BINDINGS_LIB_SYNC_HANDLE_REGISTRY_H_

#include <unordered_map>

#include "base/callback.h"
#include "base/macros.h"
#include "base/memory/ref_counted.h"
#include "base/threading/thread_checker.h"
#include "mojo/public/cpp/system/core.h"

namespace mojo {
namespace internal {

// SyncHandleRegistry is a thread-local storage to register handles that want to
// be watched together.
//
// This class is not thread safe.
class SyncHandleRegistry : public base::RefCounted<SyncHandleRegistry> {
 public:
  // Returns a thread-local object.
  static scoped_refptr<SyncHandleRegistry> current();

  using HandleCallback = base::Callback<void(MojoResult)>;
  bool RegisterHandle(const Handle& handle,
                      MojoHandleSignals handle_signals,
                      const HandleCallback& callback);

  void UnregisterHandle(const Handle& handle);

  // Waits on all the registered handles and runs callbacks synchronously for
  // those ready handles.
  // The method:
  //   - returns true when any element of |should_stop| is set to true;
  //   - returns false when any error occurs.
  bool WatchAllHandles(const bool* should_stop[], size_t count);

 private:
  friend class base::RefCounted<SyncHandleRegistry>;

  struct HandleHasher {
    size_t operator()(const Handle& handle) const {
      return std::hash<uint32_t>()(static_cast<uint32_t>(handle.value()));
    }
  };
  using HandleMap = std::unordered_map<Handle, HandleCallback, HandleHasher>;

  SyncHandleRegistry();
  ~SyncHandleRegistry();

  HandleMap handles_;

  ScopedHandle wait_set_handle_;

  base::ThreadChecker thread_checker_;

  DISALLOW_COPY_AND_ASSIGN(SyncHandleRegistry);
};

}  // namespace internal
}  // namespace mojo

#endif  // MOJO_PUBLIC_CPP_BINDINGS_LIB_SYNC_HANDLE_REGISTRY_H_