@@ -87,7 +87,7 @@ class SharedData {
87
87
}
88
88
89
89
uint32_t registerQueue (string_view vm_id, string_view queue_name, uint32_t context_id,
90
- CallOnThreadFunction call_on_thread) {
90
+ CallOnThreadFunction call_on_thread, string_view vm_key ) {
91
91
std::lock_guard<std::mutex> lock (mutex_);
92
92
auto key = std::make_pair (std::string (vm_id), std::string (queue_name));
93
93
auto it = queue_tokens_.insert (std::make_pair (key, static_cast <uint32_t >(0 )));
@@ -97,7 +97,7 @@ class SharedData {
97
97
}
98
98
uint32_t token = it.first ->second ;
99
99
auto &q = queues_[token];
100
- q.vm_id = std::string (vm_id );
100
+ q.vm_key = std::string (vm_key );
101
101
q.context_id = context_id;
102
102
q.call_on_thread = std::move (call_on_thread);
103
103
// Preserve any existing data.
@@ -127,17 +127,29 @@ class SharedData {
127
127
it->second .queue .pop_front ();
128
128
return WasmResult::Ok;
129
129
}
130
+
130
131
WasmResult enqueue (uint32_t token, string_view value) {
131
- std::lock_guard<std::mutex> lock (mutex_);
132
- auto it = queues_.find (token);
133
- if (it == queues_.end ()) {
134
- return WasmResult::NotFound;
132
+ std::string vm_key;
133
+ uint32_t context_id;
134
+ CallOnThreadFunction call_on_thread;
135
+
136
+ {
137
+ std::lock_guard<std::mutex> lock (mutex_);
138
+ auto it = queues_.find (token);
139
+ if (it == queues_.end ()) {
140
+ return WasmResult::NotFound;
141
+ }
142
+ Queue *target_queue = &(it->second );
143
+ vm_key = target_queue->vm_key ;
144
+ context_id = target_queue->context_id ;
145
+ call_on_thread = target_queue->call_on_thread ;
146
+ target_queue->queue .push_back (std::string (value));
135
147
}
136
- it-> second . queue . push_back ( std::string (value));
137
- auto vm_id = it-> second . vm_id ;
138
- auto context_id = it-> second . context_id ;
139
- it-> second . call_on_thread ([vm_id, context_id, token] {
140
- auto wasm = getThreadLocalWasm (vm_id );
148
+
149
+ call_on_thread ([vm_key, context_id, token] {
150
+ // This code may or may not execute in another thread.
151
+ // Make sure that the lock is no longer held here.
152
+ auto wasm = getThreadLocalWasm (vm_key );
141
153
if (wasm) {
142
154
auto context = wasm->wasm ()->getContext (context_id);
143
155
if (context) {
@@ -171,7 +183,7 @@ class SharedData {
171
183
}
172
184
173
185
struct Queue {
174
- std::string vm_id ;
186
+ std::string vm_key ;
175
187
uint32_t context_id;
176
188
CallOnThreadFunction call_on_thread;
177
189
std::deque<std::string> queue;
@@ -341,7 +353,7 @@ WasmResult ContextBase::registerSharedQueue(string_view queue_name,
341
353
// root.
342
354
*result = global_shared_data.registerQueue (wasm_->vm_id (), queue_name,
343
355
isRootContext () ? id_ : parent_context_id_,
344
- wasm_->callOnThreadFunction ());
356
+ wasm_->callOnThreadFunction (), wasm_-> vm_key () );
345
357
return WasmResult::Ok;
346
358
}
347
359
0 commit comments