Upgradable Read Write Lock for Go
Blog post from Upstash
In the blog post, the author explores the necessity and implementation of an upgradable read-write lock in Go, particularly in the context of enhancing concurrency performance for the Upstash RedisĀ® server. The need for this type of lock arises when managing multiple connections and operations like SUNIONSTORE that require both read and write access, which standard Go library locks couldn't handle efficiently. Initial naive attempts to solve the issue revealed problems with atomicity and deadlock when switching from read to write locks. The correct solution involved creating an upgradable read-write lock that introduces an intermediate "upgradable-read" state, allowing seamless transition to a write lock without releasing the read lock. This approach prevents deadlocks and maintains atomicity by ensuring that only one upgradable-read lock is active at a time before upgrading to a write lock. The implementation modifies the existing sync.RWMutex to accommodate the new lock type, incorporating a mechanism to track whether a lock has been upgraded or not. This innovation optimizes shared resource access in Go applications, offering a more sophisticated lock management tool for developers.