Debian Codegraph @

src/callback_registry_table.h

raw symbols SCIP
1 #ifndef _CALLBACK_REGISTRY_TABLE_H_
2 #define _CALLBACK_REGISTRY_TABLE_H_
3
4 #include <Rcpp.h>
5 #include <memory>
6 #include "threadutils.h"
7 #include "debug.h"
8 #include "callback_registry.h"
9 #include "later.h"
10
11 using std::shared_ptr;
12 using std::make_shared;
13
14 class CallbackRegistryTable;
15 extern CallbackRegistryTable callbackRegistryTable;
16
17 // ============================================================================
18 // Callback registry table
19 // ============================================================================
20 //
21 // This class is used for accessing a registry by ID. The CallbackRegistries
22 // also have a tree structure. The global loop/registry is the root. However,
23 // there can also be trees that are independent of the global loop, if a loop
24 // is created without a parent.
25 //
26 // The operations on this class are thread-safe, because they might be used to
27 // from another thread.
28 //
29 class CallbackRegistryTable {
30
31 // Basically a struct that keeps track of a registry and whether or an R loop
32 // object references it.
33 class RegistryHandle {
34 public:
35 RegistryHandle(std::shared_ptr<CallbackRegistry> registry, bool r_ref_exists)
36 : registry(registry), r_ref_exists(r_ref_exists) {
37 };
38 // Need to declare a copy constructor. Needed because pre-C++11 std::map
39 // doesn't have an .emplace() method.
40 RegistryHandle() = default;
41
42 std::shared_ptr<CallbackRegistry> registry;
43 bool r_ref_exists;
44 };
45
46 public:
47 CallbackRegistryTable() : mutex(tct_mtx_plain | tct_mtx_recursive), condvar(mutex) {
48 }
49
50 bool exists(int id) {
51 Guard guard(&mutex);
52 return (registries.find(id) != registries.end());
53 }
54
55 // Create a new CallbackRegistry. If parent_id is -1, then there is no parent.
56 void create(int id, int parent_id) {
57 ASSERT_MAIN_THREAD()
58 Guard guard(&mutex);
59
60 if (exists(id)) {
61 Rcpp::stop("Can't create event loop %d because it already exists.", id);
62 }
63
64 // Each new registry is passed our mutex and condvar. These serve as a
65 // shared lock across all CallbackRegistries and this
66 // CallbackRegistryTable. If each registry had a separate lock, some
67 // routines would recursively acquire a lock downward in the
68 // CallbackRegistry tree, and some recursively acquire a lock upward;
69 // without a shared lock, if these things happen at the same time from
70 // different threads, it could deadlock.
71 shared_ptr<CallbackRegistry> registry = make_shared<CallbackRegistry>(id, &mutex, &condvar);
72
73 if (parent_id != -1) {
74 shared_ptr<CallbackRegistry> parent = getRegistry(parent_id);
75 if (parent == nullptr) {
76 Rcpp::stop("Can't create registry. Parent with id %d does not exist.", parent_id);
77 }
78 registry->parent = parent;
79 parent->children.push_back(registry);
80 }
81
82 // Would be better to use .emplace() to avoid copy-constructor, but that
83 // requires C++11.
84 registries[id] = RegistryHandle(registry, true);
85 }
86
87 // Returns a shared_ptr to the registry. If the registry is not present in
88 // the table, or if the target CallbackRegistry has already been deleted,
89 // then the shared_ptr is empty.
90 shared_ptr<CallbackRegistry> getRegistry(int id) {
91 Guard guard(&mutex);
92 if (!exists(id)) {
93 return shared_ptr<CallbackRegistry>();
94 }
95 // If the target of the shared_ptr has been deleted, then this is an empty
96 // shared_ptr.
97 return registries[id].registry;
98 }
99
100 uint64_t scheduleCallback(void (*func)(void*), void* data, double delaySecs, int loop_id) {
101 // This method can be called from any thread
102 Guard guard(&mutex);
103
104 shared_ptr<CallbackRegistry> registry = getRegistry(loop_id);
105 if (registry == nullptr) {
106 return 0;
107 }
108 return doExecLater(registry, func, data, delaySecs, true);
109 }
110
111 // This is called when the R loop handle referring to a CallbackRegistry is
112 // destroyed. Returns true if the CallbackRegistry exists and this function
113 // has not previously been called on it; false otherwise.
114 bool notifyRRefDeleted(int id) {
115 ASSERT_MAIN_THREAD()
116 Guard guard(&mutex);
117
118 if (!exists(id)) {
119 return false;
120 }
121
122 if (registries[id].r_ref_exists) {
123 registries[id].r_ref_exists = false;
124 this->pruneRegistries();
125 return true;
126 } else {
127 return false;
128 }
129 }
130
131 // Iterate over all registries, and remove a registry when:
132 // * If the loop has a parent:
133 // * There's no R loop object referring to it, AND the registry is empty.
134 // * If the loop does not have a parent:
135 // * There's no R loop object referring to it. (Dont' need the registry to
136 // be empty, because if there's no parent and no R reference to the loop,
137 // there is no way to execute callbacks in the registry.)
138 void pruneRegistries() {
139 ASSERT_MAIN_THREAD()
140 Guard guard(&mutex);
141
142 std::map<int, RegistryHandle>::iterator it = registries.begin();
143
144 // Iterate over all registries. Remove under the following conditions:
145 // * There are no more R loop handle references to the registry, AND
146 // * The registry is empty, OR the registry has no parent.
147 // This logic is equivalent to the logic describing the function, just in
148 // a different order.
149 //
150 // std::map are sorted, and children always have a larger ID than their
151 // parents. Because of this, if there is a case where initially a child does
152 // not have any R refs, but the parent does have an R ref, then the parent's
153 // R ref is deleted, both will removed in a single pass.
154 while (it != registries.end()) {
155 if (!it->second.r_ref_exists &&
156 (it->second.registry->empty() || it->second.registry->parent == nullptr))
157 {
158 // Need to increment iterator before removing the registry; otherwise
159 // the iterator will be invalid.
160 int id = it->first;
161 it++;
162 remove(id);
163 } else {
164 it++;
165 }
166 }
167 }
168
169 // Remove a callback registry from the table
170 bool remove(int id) {
171 // Removal is always called from the main thread.
172 ASSERT_MAIN_THREAD()
173 Guard guard(&mutex);
174
175 shared_ptr<CallbackRegistry> registry = getRegistry(id);
176 if (registry == nullptr) {
177 return false;
178 }
179
180 // Deregister this object from its parent. Do it here instead of the in the
181 // CallbackRegistry destructor, for two reasons: One is that we can be 100%
182 // sure that the deregistration happens right now (it's possible that the
183 // object's destructor won't run yet, because someone else has a shared_ptr
184 // to it). Second, we can't reliably use a shared_ptr to the object from
185 // inside its destructor; we need to some pointer comparison, but by the
186 // time the destructor runs, you can't run shared_from_this() in the object,
187 // because there are no more shared_ptrs to it.
188 shared_ptr<CallbackRegistry> parent = registry->parent;
189 if (parent != nullptr) {
190 // Remove this registry from the parent's list of children.
191 for (std::vector<shared_ptr<CallbackRegistry> >::iterator it = parent->children.begin();
192 it != parent->children.end();
193 )
194 {
195 if (*it == registry) {
196 parent->children.erase(it);
197 break;
198 } else {
199 ++it;
200 }
201 }
202 }
203
204 // Tell the children that they no longer have a parent.
205 for (std::vector<std::shared_ptr<CallbackRegistry> >::iterator it = registry->children.begin();
206 it != registry->children.end();
207 ++it)
208 {
209 (*it)->parent.reset();
210 }
211
212 registries.erase(id);
213
214 return true;
215 }
216
217 private:
218 std::map<int, RegistryHandle> registries;
219 Mutex mutex;
220 ConditionVariable condvar;
221
222 };
223
224
225 #endif