Offload functions to worker threads with shared memory primitives for Node.js.
8
fork

Configure Feed

Select the types of activity you want to include in your feed.

feat(shared): add Mutex.tryLock synchronous variant

+37
+11
src/shared/mutex.ts
··· 46 46 } 47 47 } 48 48 49 + /** 50 + * Attempts to acquire the lock without waiting. 51 + * @returns A disposable {@link MutexGuard} if acquired, otherwise `null`. 52 + */ 53 + tryLock(): MutexGuard | null { 54 + if (Atomics.compareExchange(this.view, 0, UNLOCKED, LOCKED) === UNLOCKED) { 55 + return new MutexGuard(this); 56 + } 57 + return null; 58 + } 59 + 49 60 /** Releases the lock and wakes one waiting thread. */ 50 61 unlock(): void { 51 62 Atomics.store(this.view, 0, UNLOCKED);
+26
test/shared/mutex.test.ts
··· 51 51 it('exposes byteSize of 4', () => { 52 52 assert.equal(mutex.byteSize, 4); 53 53 }); 54 + 55 + it('tryLock returns a guard when unlocked', () => { 56 + const m = mutex(); 57 + const guard = m.tryLock(); 58 + assert.ok(guard); 59 + assert.equal(typeof guard[Symbol.dispose], 'function'); 60 + m.unlock(); 61 + }); 62 + 63 + it('tryLock returns null when held', async () => { 64 + const m = mutex(); 65 + await m.lock(); 66 + const guard = m.tryLock(); 67 + assert.equal(guard, null); 68 + m.unlock(); 69 + }); 70 + 71 + it('tryLock succeeds again after unlock', () => { 72 + const m = mutex(); 73 + const g1 = m.tryLock(); 74 + assert.ok(g1); 75 + m.unlock(); 76 + const g2 = m.tryLock(); 77 + assert.ok(g2); 78 + m.unlock(); 79 + }); 54 80 });