mirror of
https://github.com/robonen/tools.git
synced 2026-03-20 19:04:46 +00:00
feat(packages/stdlib): add SyncMutex
This commit is contained in:
@@ -5,6 +5,7 @@ export * from './math';
|
||||
export * from './objects';
|
||||
export * from './patterns';
|
||||
export * from './structs';
|
||||
export * from './sync';
|
||||
export * from './text';
|
||||
export * from './types';
|
||||
export * from './utils'
|
||||
|
||||
1
packages/stdlib/src/sync/index.ts
Normal file
1
packages/stdlib/src/sync/index.ts
Normal file
@@ -0,0 +1 @@
|
||||
export * from './mutex';
|
||||
45
packages/stdlib/src/sync/mutex/index.test.ts
Normal file
45
packages/stdlib/src/sync/mutex/index.test.ts
Normal 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);
|
||||
});
|
||||
});
|
||||
29
packages/stdlib/src/sync/mutex/index.ts
Normal file
29
packages/stdlib/src/sync/mutex/index.ts
Normal 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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user