-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathlock.test.ts
73 lines (59 loc) · 2.03 KB
/
lock.test.ts
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
import { deepStrictEqual, strictEqual } from "node:assert";
import { sleep } from "./async.ts";
import { Mutex } from "./lock.ts";
import jsext, { _try } from "./index.ts";
describe("jsext.lock", () => {
it("lock", async () => {
const key = 1;
const results: number[] = [];
await Promise.all([
jsext.func(async (defer) => {
const lock = await jsext.lock(key);
defer(() => lock.unlock());
await sleep(50);
results.push(1);
})(),
jsext.func(async (defer) => {
const lock = await jsext.lock(key);
defer(() => lock.unlock());
await sleep(40);
results.push(2);
})(),
]);
deepStrictEqual(results, [1, 2]);
});
it("Mutex", async () => {
const mutex = new Mutex(1);
let value = 1;
await Promise.all([
(async () => {
using lock = await mutex.lock();
// defer(() => lock.unlock());
await sleep(50);
lock.value = 2;
})(),
(async () => {
using lock = await mutex.lock();
// defer(() => lock.unlock());
await sleep(40);
lock.value = 3;
})(),
(async () => {
using lock = await mutex.lock();
// defer(() => lock.unlock());
await sleep(30);
value = lock.value;
})(),
]);
strictEqual(value, 3);
});
it("access after unlocked", async () => {
const mutex = new Mutex(1);
const lock = await mutex.lock();
lock.unlock();
const [err1] = _try(() => lock.value);
deepStrictEqual(err1, new ReferenceError("trying to access data after unlocked"));
const [err2] = _try(() => { lock.value = 2; });
deepStrictEqual(err2, new ReferenceError("trying to access data after unlocked"));
});
});