Skip to content

Commit

Permalink
fix: lock disposable acquire (#295)
Browse files Browse the repository at this point in the history
  • Loading branch information
Jujulego authored Nov 27, 2023
1 parent 3ee6f41 commit fd1f00e
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 9 deletions.
12 changes: 12 additions & 0 deletions .idea/runConfigurations/build.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@jujulego/utils",
"version": "3.0.2",
"version": "3.0.3",
"license": "MIT",
"author": "Julien Capellari <julien.capellari@gmail.com>",
"repository": {
Expand All @@ -25,7 +25,7 @@
"scripts": {
"lint": "eslint .",
"clean": "shx rm -r dist",
"build": "jill group 'build:esm // build:types'",
"build": "jill run 'build:esm // build:types'",
"build:esm": "swc -d dist src",
"build:types": "tsc --project tsconfig.build.json",
"test": "vitest run",
Expand Down
12 changes: 5 additions & 7 deletions src/lock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,21 @@ import { Condition } from './condition.js';
import { Awaitable } from './types.js';

// Class
export class Lock implements Disposable {
export class Lock {
// Attributes
private _count = 0;
private readonly _locked = new Condition(() => this._count > 0);

// Methods
async acquire(): Promise<this> {
async acquire(): Promise<Disposable> {
await this._locked.waitFor(false);

this._count++;
this._locked.check();

return this;
return {
[Symbol.dispose ?? Symbol.for('Symbol.dispose')]: () => this.release(),
};
}

release(): void {
Expand All @@ -29,10 +31,6 @@ export class Lock implements Disposable {
return fn();
}

[Symbol.dispose](): void {
this.release();
}

// Properties
get locked(): boolean {
return this._locked.value;
Expand Down

0 comments on commit fd1f00e

Please sign in to comment.