-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
51 lines (46 loc) · 1.04 KB
/
Copy pathindex.js
File metadata and controls
51 lines (46 loc) · 1.04 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
import { Queue } from "./queue.js";
function sleep(ms = 2000) {
return new Promise((resolve) => setTimeout(() => resolve(true), ms));
}
/**
* @param {Queue} q - queue object
* @param {number} readerId - Reader id
*/
async function reader(q, readerId) {
while (true) {
try {
await sleep();
const data = await q.read();
console.log(`[Reader ${readerId}] Received ::`, data);
} catch (error) {
console.log(`[Reader Error ${readerId}] ::`, error);
}
}
}
/**
* @param {Queue} q - queue object
* @param {number} writerId - Reader id
*/
async function writer(q, writerId) {
let i = 0;
while (i < 40) {
try {
// await sleep(4000);
const msg = `msg_${writerId}${++i}`;
await q.write(msg);
console.log(`[Writer] ::`, msg);
} catch (error) {
console.log(`[Writer Error] ::`, error);
}
}
}
function run() {
const queue = new Queue();
for (let i = 0; i < 20; i++) {
reader(queue, `${i + 1}`);
}
for (let i = 0; i < 2; i++) {
writer(queue, `${i + 1}`);
}
}
run();