Skip to content

fix(package): [concurrency] hold the map lock while taking the try lock - #417

Merged
duke-git merged 2 commits into
duke-git:rcfrom
lee3Q:fix/trykeyedlocker-mutual-exclusion
Nov 9, 2026
Merged

duke-git merged 2 commits into
duke-git:rcfrom
lee3Q:fix/trykeyedlocker-mutual-exclusion

Conversation

@lee3Q

@lee3Q lee3Q commented Nov 4, 2026

Copy link
Copy Markdown

TryKeyedLocker.TryLock looks up or creates the key's casMutex while holding l.mu, releases l.mu, and only then calls lock.TryLock(). Unlock removes the map entry when the lock is free. If Unlock runs between the lookup and the CAS, the goroutine in TryLock takes a lock that is no longer in the map, and a later TryLock for the same key creates a new entry and also succeeds, so two goroutines hold the same key. The race detector also reports the unsynchronized read of the lock word in Unlock against the CAS outside the mutex.

TryLock now keeps l.mu held (with defer) through lock.TryLock(). The CAS does not block, so no waiting is added, and a failed try leaves the state unchanged. Unlock is unchanged.

Test: TestTryKeyedLocker_MutualExclusionUnderContention runs 8 goroutines x 20000 iterations of TryLock, count holders, Unlock on one key and fails if a second holder is seen. It is a stress test, so a pass is not proof that the race is absent. On go1.26.6 Linux, on the base commit the test failed in 5 of 5 runs and the race detector flagged the base as well. With the change, 5 of 5 runs and -count=30 pass, go test -race ./concurrency passes, and vet and a 386 build and run pass. The change makes the critical section one CAS longer and I did not benchmark it. The full go test ./... still fails in netutil (TestTelnetConnected, ExampleIsTelnetConnected) the same way on the base commit in my environment, which has no external network access. I did not investigate the cause.

Not changed: KeyedLocker and RWKeyedLocker. In particular KeyedLocker.Do still waits for fn to finish in its deferred release when the context has already expired and no other caller holds the key.

@duke-git
duke-git merged commit b09d6af into duke-git:rc Nov 9, 2026
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants