Skip to content

Commit

Permalink
Fixed order of operations for RWLocks by yielding for all microtasks …
Browse files Browse the repository at this point in the history
…even if not first reader
  • Loading branch information
CMCDragonkai committed Apr 1, 2022
1 parent f6463f9 commit 8d421c0
Show file tree
Hide file tree
Showing 4 changed files with 10 additions and 8 deletions.
3 changes: 3 additions & 0 deletions src/RWLockReader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,9 @@ class RWLockReader {
--this._readerCount;
throw e;
}
} else {
// Yield for the first reader to finish locking
await yieldMicro();
}
return [
async () => {
Expand Down
3 changes: 3 additions & 0 deletions src/RWLockWriter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,9 @@ class RWLockWriter {
--this._readerCount;
throw e;
}
} else {
// Yield for the first reader to finish locking
await yieldMicro();
}
return [
async () => {
Expand Down
6 changes: 2 additions & 4 deletions tests/RWLockReader.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string> = [];
const p1 = lock.withReadF(async () => {
Expand All @@ -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',
]);
Expand Down
6 changes: 2 additions & 4 deletions tests/RWLockWriter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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',
]);
});
Expand Down

0 comments on commit 8d421c0

Please sign in to comment.