Skip to content

Commit

Permalink
feat(Lock): use RawSemaphore to improve performance
Browse files Browse the repository at this point in the history
  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
  • Loading branch information
lambdalisue committed Aug 17, 2024
1 parent 6b093da commit 9f3b7eb
Showing 1 changed file with 5 additions and 5 deletions.
10 changes: 5 additions & 5 deletions lock.ts
Original file line number Diff line number Diff line change
@@ -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.
Expand All @@ -16,7 +16,7 @@ import { Mutex } from "./mutex.ts";
* ```
*/
export class Lock<T> {
#mu = new Mutex();
#sem = new RawSemaphore(1);
#value: T;

/**
Expand All @@ -32,7 +32,7 @@ export class Lock<T> {
* Returns true if the lock is currently locked, false otherwise.
*/
get locked(): boolean {
return this.#mu.locked;
return this.#sem.locked;
}

/**
Expand All @@ -43,11 +43,11 @@ export class Lock<T> {
* @returns A Promise that resolves with the result of the function.
*/
async lock<R>(fn: (value: T) => R | PromiseLike<R>): Promise<R> {
const lock = await this.#mu.acquire();
await this.#sem.acquire();
try {
return await fn(this.#value);
} finally {
lock[Symbol.dispose]();
this.#sem.release();
}
}
}

0 comments on commit 9f3b7eb

Please sign in to comment.