From 9f3b7eb53679db47e02c20e7b6406fd4f825c7fc Mon Sep 17 00:00:00 2001 From: Alisue Date: Sat, 17 Aug 2024 04:32:32 +0900 Subject: [PATCH] feat(Lock): use `RawSemaphore` to improve performance MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit benchmark time (avg) iter/s (min … max) p75 p99 p995 --------------------------------------------------------------- ----------------------------- group Lock#lock current 231.74 µs/iter 4,315.2 (206.46 µs … 700.42 µs) 215.5 µs 488.58 µs 505.96 µs v1.0.0 52.28 ms/iter 19.1 (47.25 ms … 55.24 ms) 54.78 ms 55.24 ms 55.24 ms summary current 225.59x faster than v1.0.0 --- lock.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/lock.ts b/lock.ts index 2b5d955..7afa1ee 100644 --- a/lock.ts +++ b/lock.ts @@ -1,4 +1,4 @@ -import { Mutex } from "./mutex.ts"; +import { RawSemaphore } from "./_raw_semaphore.ts"; /** * A mutual exclusion lock that provides safe concurrent access to a shared value. @@ -16,7 +16,7 @@ import { Mutex } from "./mutex.ts"; * ``` */ export class Lock { - #mu = new Mutex(); + #sem = new RawSemaphore(1); #value: T; /** @@ -32,7 +32,7 @@ export class Lock { * Returns true if the lock is currently locked, false otherwise. */ get locked(): boolean { - return this.#mu.locked; + return this.#sem.locked; } /** @@ -43,11 +43,11 @@ export class Lock { * @returns A Promise that resolves with the result of the function. */ async lock(fn: (value: T) => R | PromiseLike): Promise { - const lock = await this.#mu.acquire(); + await this.#sem.acquire(); try { return await fn(this.#value); } finally { - lock[Symbol.dispose](); + this.#sem.release(); } } }