-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy path4-race-condition.js
More file actions
56 lines (49 loc) · 1.11 KB
/
4-race-condition.js
File metadata and controls
56 lines (49 loc) · 1.11 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
'use strict';
const threads = require('node:worker_threads');
const { Worker, isMainThread } = threads;
class Point {
constructor(data, x, y) {
this.data = data;
if (typeof x === 'number') data[0] = x;
if (typeof y === 'number') data[1] = y;
}
get x() {
return this.data[0];
}
set x(value) {
this.data[0] = value;
}
get y() {
return this.data[1];
}
set y(value) {
this.data[1] = value;
}
move(x, y) {
this.x += x;
this.y += y;
}
}
// Usage
if (isMainThread) {
const buffer = new SharedArrayBuffer(4);
const array = new Int8Array(buffer, 0, 2);
const point = new Point(array, 0, 0);
console.dir({ buffer, point });
new Worker(__filename, { workerData: buffer });
new Worker(__filename, { workerData: buffer });
} else {
const { threadId, workerData } = threads;
const array = new Int8Array(workerData, 0, 2);
const point = new Point(array);
if (threadId === 1) {
for (let i = 0; i < 1000000; i++) {
point.move(1, 1);
}
} else {
for (let i = 0; i < 1000000; i++) {
point.move(-1, -1);
}
}
console.dir({ point });
}