@@ -13,7 +13,7 @@ class RequestResponseSynchronizer {
1313 static const _responseIndex = 1 ;
1414
1515 // 2 32-bit slots for the int32 array
16- static const byteLength = 2 * 4 ;
16+ static const _byteLength = 2 * 4 ;
1717
1818 /// The shared array buffer used with atomics for synchronization.
1919 ///
@@ -26,17 +26,32 @@ class RequestResponseSynchronizer {
2626 RequestResponseSynchronizer ._(this .buffer) : int32View = buffer.asInt32List ();
2727
2828 factory RequestResponseSynchronizer ([SharedArrayBuffer ? buffer]) {
29- if (buffer != null && buffer.byteLength != byteLength ) {
30- throw ArgumentError ('Must be $byteLength in length' );
29+ if (buffer != null && buffer.byteLength != _byteLength ) {
30+ throw ArgumentError ('Must be $_byteLength in length' );
3131 }
3232
3333 return RequestResponseSynchronizer ._(
34- buffer ?? SharedArrayBuffer (byteLength));
34+ buffer ?? SharedArrayBuffer (_byteLength));
35+ }
36+
37+ /// Creates a shared buffer and fills it with the initial state suitable for
38+ /// a request synchronization channel.
39+ static SharedArrayBuffer createBuffer () {
40+ final buffer = SharedArrayBuffer (_byteLength);
41+ final view = buffer.asInt32List ();
42+
43+ // The server will wait for the request index to not be -1 to wait for a
44+ // request. The initial value when allocating shared buffers is 0, which is
45+ // also a valid opcode.
46+ Atomics .store (view, _requestIndex, - 1 );
47+
48+ return buffer;
3549 }
3650
3751 /// Send a request with the given [opcode] , wait for the remote worker to
3852 /// process it and returns the response code.
3953 int requestAndWaitForResponse (int opcode) {
54+ assert (opcode >= 0 );
4055 Atomics .store (int32View, _responseIndex, - 1 );
4156 Atomics .store (int32View, _requestIndex, opcode);
4257 Atomics .notify (int32View, _requestIndex);
@@ -49,16 +64,17 @@ class RequestResponseSynchronizer {
4964
5065 String waitForRequest () {
5166 return Atomics .waitWithTimeout (
52- int32View, _requestIndex, 0 , asyncIdleWaitTimeMs);
67+ int32View, _requestIndex, - 1 , asyncIdleWaitTimeMs);
5368 }
5469
5570 int takeOpcode () {
5671 final opcode = Atomics .load (int32View, _requestIndex);
57- Atomics .store (int32View, _requestIndex, 0 );
72+ Atomics .store (int32View, _requestIndex, - 1 );
5873 return opcode;
5974 }
6075
6176 void respond (int rc) {
77+ assert (rc != - 1 );
6278 Atomics .store (int32View, _responseIndex, rc);
6379 Atomics .notify (int32View, _responseIndex);
6480 }
0 commit comments