Skip to content

Instantly share code, notes, and snippets.

@3AHAT0P
Created November 12, 2025 08:52
Show Gist options
  • Select an option

  • Save 3AHAT0P/6a38cea25f1dfd7d4ddf0b560c5f2a6a to your computer and use it in GitHub Desktop.

Select an option

Save 3AHAT0P/6a38cea25f1dfd7d4ddf0b560c5f2a6a to your computer and use it in GitHub Desktop.
Implementation Mutex based on Promise logic in TypeScript
class AsyncMutex {
private _locked = false;
private _waiting: (() => void)[] = [];
constructor() {
this._unlock = this._unlock.bind(this);
}
async lock(): Promise<() => void> {
if (!this._locked) {
this._locked = true;
return this._unlock;
} else {
this._locked = true;
return new Promise<() => void>(resolve => {
this._waiting.push(() => resolve(this._unlock));
});
}
}
private _unlock() {
if (this._waiting.length > 0) {
const next = this._waiting.shift();
next!();
}
if (this._waiting.length === 0) this._locked = false;
}
}
const mutex = new AsyncMutex();
async function criticalSection(id: number) {
const unlock = await mutex.lock();
try {
console.log(`Task ${id} entered critical section`);
await new Promise(r => setTimeout(r, 1000)); // имитация async-работы
console.log(`Task ${id} leaving critical section`);
} finally {
unlock(); // обязательно освобождаем
}
}
const main = async () => {
for (let i = 1; i <= 3; i++) {
criticalSection(i);
}
await new Promise(r => setTimeout(r, 5 * 1000)); // имитация async-работы
for (let i = 10; i <= 13; i++) {
criticalSection(i);
}
for (let i = 20; i <= 23; i++) {
criticalSection(i);
}
};
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment