-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path5-async.js
More file actions
81 lines (70 loc) · 1.74 KB
/
Copy path5-async.js
File metadata and controls
81 lines (70 loc) · 1.74 KB
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
'use strict';
// Async producer–consumer
// over a fixed ring buffer with waiters
class AsyncRingBuffer {
constructor(capacity) {
this.capacity = capacity;
this.buffer = new Array(capacity);
this.head = 0;
this.tail = 0;
this.length = 0;
this.waiters = { put: [], take: [] };
}
#wake(kind) {
const next = this.waiters[kind].shift();
if (next) next();
}
put(value) {
return new Promise((resolve) => {
const tryPut = () => {
if (this.length < this.capacity) {
this.buffer[this.tail] = value;
this.tail = (this.tail + 1) % this.capacity;
this.length++;
this.#wake('take');
resolve(true);
return;
}
this.waiters.put.push(tryPut);
};
tryPut();
});
}
take() {
return new Promise((resolve) => {
const tryTake = () => {
if (this.length > 0) {
const value = this.buffer[this.head];
this.buffer[this.head] = undefined;
this.head = (this.head + 1) % this.capacity;
this.length--;
this.#wake('put');
resolve(value);
return;
}
this.waiters.take.push(tryTake);
};
tryTake();
});
}
}
// Usage
const channel = new AsyncRingBuffer(2);
const messages = ['Meditations', 'Letters', 'Discourses', 'Enchiridion'];
const producer = async () => {
for (const msg of messages) {
await channel.put(msg);
console.log('produced:', msg);
}
};
const consumer = async () => {
for (let i = 0; i < messages.length; i++) {
const msg = await channel.take();
console.log('consumed:', msg);
}
};
const main = async () => {
await Promise.all([producer(), consumer()]);
console.log('done');
};
main();