Skip to content

Commit 19f6f95

Browse files
authored
Avoid constantly attempting to acquire a lock (#491)
- ignore expiration timeout on WaitForChangesAsync when there are queued writer locks
1 parent 8c5f802 commit 19f6f95

1 file changed

Lines changed: 13 additions & 10 deletions

File tree

src/Machine/src/Serval.Machine.Shared/Services/DistributedReaderWriterLock.cs

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -73,8 +73,8 @@ public async Task<T> ReaderLockAsync<T>(
7373
RWLock? rwLock = sub.Change.Entity;
7474
if (rwLock is not null && !rwLock.IsAvailableForReading())
7575
{
76-
TimeSpan? timeout = default;
77-
if (rwLock.WriterLock?.ExpiresAt is not null)
76+
TimeSpan? timeout = null;
77+
if (rwLock.WriterQueue.Count == 0 && rwLock.WriterLock?.ExpiresAt is not null)
7878
{
7979
timeout = rwLock.WriterLock.ExpiresAt - DateTime.UtcNow;
8080
if (timeout < TimeSpan.Zero)
@@ -138,15 +138,18 @@ await _locks.UpdateAsync(
138138
RWLock? rwLock = sub.Change.Entity;
139139
if (rwLock is not null && !rwLock.IsAvailableForWriting(lockId))
140140
{
141-
var dateTimes = rwLock.ReaderLocks.Select(l => l.ExpiresAt).ToList();
142-
if (rwLock.WriterLock?.ExpiresAt is not null)
143-
dateTimes.Add(rwLock.WriterLock.ExpiresAt);
144-
TimeSpan? timeout = default;
145-
if (dateTimes.Count > 0)
141+
TimeSpan? timeout = null;
142+
if (rwLock.WriterQueue[0].Id == lockId)
146143
{
147-
timeout = dateTimes.Max() - DateTime.UtcNow;
148-
if (timeout < TimeSpan.Zero)
149-
timeout = TimeSpan.Zero;
144+
var dateTimes = rwLock.ReaderLocks.Select(l => l.ExpiresAt).ToList();
145+
if (rwLock.WriterLock?.ExpiresAt is not null)
146+
dateTimes.Add(rwLock.WriterLock.ExpiresAt);
147+
if (dateTimes.Count > 0)
148+
{
149+
timeout = dateTimes.Max() - DateTime.UtcNow;
150+
if (timeout < TimeSpan.Zero)
151+
timeout = TimeSpan.Zero;
152+
}
150153
}
151154
if (timeout != TimeSpan.Zero)
152155
await sub.WaitForChangeAsync(timeout, cancellationToken);

0 commit comments

Comments
 (0)