-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrwmutex.test.js
106 lines (92 loc) · 2.05 KB
/
rwmutex.test.js
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
const RWMutex = require("../src/rwmutex")
const sleep = require("../src/helpers/sleep")
describe("Simple tests", () => {
let rwmutex = undefined
let readersInCs = 0
let writersInCs = 0
const CSJob = async (workerType) => {
switch (workerType) {
case "reader":
++readersInCs
if (writersInCs > 0) {
throw "reader with writer"
}
break
case "writer":
++writersInCs
if (writersInCs > 1) {
throw "a few writers in cs"
}
if (readersInCs > 0) {
throw "writer with reader"
}
break
default:
throw `unsupported ${workerType}`
}
await sleep(1e-4 * Math.random())
switch (workerType) {
case "reader":
--readersInCs
break
case "writer":
--writersInCs
break
}
}
const execute = async (cb, type) => {
if (type === "reader") {
await rwmutex.RLock()
} else if (type === "writer") {
await rwmutex.Lock()
} else {
throw "unsupported"
}
await cb(type)
if (type === "reader") {
await rwmutex.RUnLock()
} else if (type === "writer") {
await rwmutex.UnLock()
} else {
throw "unsupported"
}
}
afterEach(() => {
rwmutex = undefined
threadsInCs = 0
})
beforeEach(() => {
rwmutex = new RWMutex()
threadsInCs = 0
})
test("reader and writer", async () => {
await Promise.all([
execute(CSJob, "reader"),
execute(CSJob, "writer"),
])
})
test("a few writers", async () => {
await Promise.all(
Array(50)
.fill()
.map(() => execute(CSJob, "writer"))
)
})
test("a few readers", async () => {
await Promise.all(
Array(50)
.fill()
.map(() => execute(CSJob, "reader"))
)
})
test("readers and writers", async () => {
await Promise.all([
...Array(500)
.fill()
.map(() => execute(CSJob, "reader")),
...Array(500)
.fill()
.map(() => execute(CSJob, "writer")),
])
})
})