Skip to content

Commit

Permalink
feat(Semaphore): add lockedSize to reveal the number of locked reso…
Browse files Browse the repository at this point in the history
…urces
  • Loading branch information
lambdalisue committed Sep 24, 2024
1 parent c4ec010 commit 247d236
Show file tree
Hide file tree
Showing 3 changed files with 67 additions and 0 deletions.
7 changes: 7 additions & 0 deletions _raw_semaphore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,13 @@ export class RawSemaphore {
return this.#value === 0;
}

/**
* Returns the number of currently locked operations.
*/
get lockedSize(): number {
return this.#resolves.length;
}

/**
* Acquires the semaphore, blocking until the semaphore is available.
*/
Expand Down
7 changes: 7 additions & 0 deletions semaphore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,13 @@ export class Semaphore {
return this.#sem.locked;
}

/**
* Returns the number of currently locked operations.
*/
get lockedSize(): number {
return this.#sem.lockedSize;
}

/**
* Acquires a lock on the semaphore, and invokes the specified function.
*
Expand Down
53 changes: 53 additions & 0 deletions semaphore_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,3 +106,56 @@ test(
assertThrows(() => new Semaphore(0), RangeError);
},
);

test(
"Semaphore.lockedSize returns the number of locked operations (n=5)",
async () => {
const befores: number[] = [];
const afters: number[] = [];
const sem = new Semaphore(5);
const worker = (i: number) => {
return sem.lock(async () => {
befores.push(sem.lockedSize);
await new Promise((resolve) => setTimeout(resolve, 10 + i));
afters.push(sem.lockedSize);
});
};
await Promise.all([...Array(10)].map((_, i) => worker(i)));
/**
* Worker 0 |5========5
* Worker 1 |5=========4
* Worker 2 |5==========3
* Worker 3 |5===========2
* Worker 4 |5============1
* Worker 5 |----------4=============0
* Worker 6 |-----------3==============0
* Worker 7 |------------2===============0
* Worker 8 |-------------1================0
* Worker 9 |--------------0=================0
*/
assertEquals(befores, [
5,
5,
5,
5,
5,
4,
3,
2,
1,
0,
]);
assertEquals(afters, [
5,
4,
3,
2,
1,
0,
0,
0,
0,
0,
]);
},
);

0 comments on commit 247d236

Please sign in to comment.