diff --git a/src/RWLockReader.ts b/src/RWLockReader.ts index c2dc327..3434de8 100644 --- a/src/RWLockReader.ts +++ b/src/RWLockReader.ts @@ -29,6 +29,9 @@ class RWLockReader { --this._readerCount; throw e; } + } else { + // Yield for the first reader to finish locking + await yieldMicro(); } return [ async () => { diff --git a/src/RWLockWriter.ts b/src/RWLockWriter.ts index a806fad..96367e2 100644 --- a/src/RWLockWriter.ts +++ b/src/RWLockWriter.ts @@ -57,6 +57,9 @@ class RWLockWriter { --this._readerCount; throw e; } + } else { + // Yield for the first reader to finish locking + await yieldMicro(); } return [ async () => { diff --git a/tests/RWLockReader.test.ts b/tests/RWLockReader.test.ts index 2f100fe..db07669 100644 --- a/tests/RWLockReader.test.ts +++ b/tests/RWLockReader.test.ts @@ -315,7 +315,7 @@ describe(RWLockReader.name, () => { expect(value).toBe(2); }); test('order of operations', async () => { - // Write-preferring order + // Read-preferring order const lock = new RWLockReader(); const order: Array = []; const p1 = lock.withReadF(async () => { @@ -342,13 +342,11 @@ describe(RWLockReader.name, () => { await p4; await p5; await p6; - // Notice that `read2` happens first - // This can chnage if `read2` takes longer to do expect(order).toStrictEqual([ + 'read1', 'read2', 'read3', 'read4', - 'read1', 'write1', 'write2', ]); diff --git a/tests/RWLockWriter.test.ts b/tests/RWLockWriter.test.ts index 3fc08b5..f1bae6f 100644 --- a/tests/RWLockWriter.test.ts +++ b/tests/RWLockWriter.test.ts @@ -342,14 +342,12 @@ describe(RWLockWriter.name, () => { await p4; await p5; await p6; - // Notice that `read2` happens first - // This can chnage if `read2` takes longer to do expect(order).toStrictEqual([ - 'read2', 'read1', + 'read2', 'write1', - 'read4', 'read3', + 'read4', 'write2', ]); });