@@ -13,7 +13,7 @@ class RequestResponseSynchronizer {
13
13
static const _responseIndex = 1 ;
14
14
15
15
// 2 32-bit slots for the int32 array
16
- static const byteLength = 2 * 4 ;
16
+ static const _byteLength = 2 * 4 ;
17
17
18
18
/// The shared array buffer used with atomics for synchronization.
19
19
///
@@ -26,17 +26,32 @@ class RequestResponseSynchronizer {
26
26
RequestResponseSynchronizer ._(this .buffer) : int32View = buffer.asInt32List ();
27
27
28
28
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' );
31
31
}
32
32
33
33
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;
35
49
}
36
50
37
51
/// Send a request with the given [opcode] , wait for the remote worker to
38
52
/// process it and returns the response code.
39
53
int requestAndWaitForResponse (int opcode) {
54
+ assert (opcode >= 0 );
40
55
Atomics .store (int32View, _responseIndex, - 1 );
41
56
Atomics .store (int32View, _requestIndex, opcode);
42
57
Atomics .notify (int32View, _requestIndex);
@@ -49,16 +64,17 @@ class RequestResponseSynchronizer {
49
64
50
65
String waitForRequest () {
51
66
return Atomics .waitWithTimeout (
52
- int32View, _requestIndex, 0 , asyncIdleWaitTimeMs);
67
+ int32View, _requestIndex, - 1 , asyncIdleWaitTimeMs);
53
68
}
54
69
55
70
int takeOpcode () {
56
71
final opcode = Atomics .load (int32View, _requestIndex);
57
- Atomics .store (int32View, _requestIndex, 0 );
72
+ Atomics .store (int32View, _requestIndex, - 1 );
58
73
return opcode;
59
74
}
60
75
61
76
void respond (int rc) {
77
+ assert (rc != - 1 );
62
78
Atomics .store (int32View, _responseIndex, rc);
63
79
Atomics .notify (int32View, _responseIndex);
64
80
}
0 commit comments