1
0
mirror of https://github.com/robonen/tools.git synced 2026-03-20 02:44:45 +00:00

feat(packages/stdlib): add SyncMutex

This commit is contained in:
2025-02-23 00:44:14 +07:00
parent fad1284cd3
commit 8c5252986e
4 changed files with 76 additions and 0 deletions

View File

@@ -5,6 +5,7 @@ export * from './math';
export * from './objects'; export * from './objects';
export * from './patterns'; export * from './patterns';
export * from './structs'; export * from './structs';
export * from './sync';
export * from './text'; export * from './text';
export * from './types'; export * from './types';
export * from './utils' export * from './utils'

View File

@@ -0,0 +1 @@
export * from './mutex';

View File

@@ -0,0 +1,45 @@
import { describe, it, expect, beforeEach } from 'vitest';
import { SyncMutex } from '.';
describe('SyncMutex', () => {
let mutex: SyncMutex;
beforeEach(() => {
mutex = new SyncMutex();
});
it('unlocked by default', () => {
expect(mutex.isLocked).toBe(false);
});
it('lock the mutex', () => {
mutex.lock();
expect(mutex.isLocked).toBe(true);
});
it('remain locked when locked multiple times', () => {
mutex.lock();
mutex.lock();
expect(mutex.isLocked).toBe(true);
});
it('unlock a locked mutex', () => {
mutex.lock();
mutex.unlock();
expect(mutex.isLocked).toBe(false);
});
it('remain unlocked when unlocked multiple times', () => {
mutex.unlock();
mutex.unlock();
expect(mutex.isLocked).toBe(false);
});
it('reflect the current lock state', () => {
expect(mutex.isLocked).toBe(false);
mutex.lock();
expect(mutex.isLocked).toBe(true);
mutex.unlock();
expect(mutex.isLocked).toBe(false);
});
});

View File

@@ -0,0 +1,29 @@
/**
* @name SyncMutex
* @category Utils
* @description A simple synchronous mutex to provide more readable locking and unlocking of code blocks
*
* @example
* const mutex = new SyncMutex();
*
* mutex.lock();
*
* mutex.unlock();
*
* @since 0.0.5
*/
export class SyncMutex {
private state: boolean = false;
public get isLocked() {
return this.state;
}
public lock() {
this.state = true;
}
public unlock() {
this.state = false;
}
}