├── .github └── workflows │ └── test.yml ├── LICENSE ├── README.md ├── go.mod ├── mutexmap.go ├── mutexmap_test.go ├── rwmutexmap.go └── rwmutexmap_test.go /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: Run go test 2 | 3 | on: 4 | push: 5 | branches: [ 'main' ] 6 | pull_request: 7 | 8 | jobs: 9 | test: 10 | name: Test 11 | permissions: 12 | contents: read 13 | strategy: 14 | matrix: 15 | go-version: 16 | - stable 17 | - oldstable 18 | - 1.19.x 19 | os: [ubuntu-latest] 20 | runs-on: ${{ matrix.os }} 21 | steps: 22 | - uses: actions/checkout@v4 23 | - name: Install Go 24 | uses: actions/setup-go@v5 25 | with: 26 | go-version: ${{ matrix.go-version }} 27 | - name: Test 28 | run: go test -v ./... 29 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | https://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | Copyright 2013-2018 Docker, Inc. 179 | 180 | Licensed under the Apache License, Version 2.0 (the "License"); 181 | you may not use this file except in compliance with the License. 182 | You may obtain a copy of the License at 183 | 184 | https://www.apache.org/licenses/LICENSE-2.0 185 | 186 | Unless required by applicable law or agreed to in writing, software 187 | distributed under the License is distributed on an "AS IS" BASIS, 188 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 189 | See the License for the specific language governing permissions and 190 | limitations under the License. 191 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Locker 2 | ===== 3 | 4 | locker provides a mechanism for creating finer-grained locking to help 5 | free up more global locks to handle other tasks. 6 | 7 | The implementation looks close to a sync.Mutex, however, the user must provide a 8 | reference to use to refer to the underlying lock when locking and unlocking. 9 | 10 | If a lock with a given name does not exist when `Lock` is called, one is 11 | created. 12 | Lock references are automatically cleaned up on `Unlock` if nothing else is 13 | waiting for the lock. 14 | 15 | 16 | ## Usage 17 | 18 | ```go 19 | package important 20 | 21 | import ( 22 | "sync" 23 | "time" 24 | 25 | "github.com/moby/locker/v2" 26 | ) 27 | 28 | type important struct { 29 | locks locker.MutexMap[string] 30 | data map[string]interface{} 31 | mu sync.Mutex 32 | } 33 | 34 | func (i *important) Get(name string) interface{} { 35 | i.locks.Lock(name) 36 | defer i.locks.Unlock(name) 37 | return i.data[name] 38 | } 39 | 40 | func (i *important) Create(name string, data interface{}) { 41 | i.locks.Lock(name) 42 | defer i.locks.Unlock(name) 43 | 44 | i.createImportant(data) 45 | 46 | i.mu.Lock() 47 | i.data[name] = data 48 | i.mu.Unlock() 49 | } 50 | 51 | func (i *important) createImportant(data interface{}) { 52 | time.Sleep(10 * time.Second) 53 | } 54 | ``` 55 | 56 | For functions dealing with a given name, always lock at the beginning of the 57 | function (or before doing anything with the underlying state), this ensures any 58 | other function that is dealing with the same name will block. 59 | 60 | When needing to modify the underlying data, use the global lock to ensure nothing 61 | else is modifying it at the same time. 62 | Since name lock is already in place, no reads will occur while the modification 63 | is being performed. 64 | 65 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/moby/locker/v2 2 | 3 | go 1.19 4 | -------------------------------------------------------------------------------- /mutexmap.go: -------------------------------------------------------------------------------- 1 | /* 2 | Package locker provides a mechanism for creating finer-grained locking to help 3 | free up more global locks to handle other tasks. 4 | */ 5 | package locker 6 | 7 | import ( 8 | "sync" 9 | "sync/atomic" 10 | ) 11 | 12 | // MutexMap is a more convenient map[T]sync.Mutex. It automatically makes and 13 | // deletes mutexes as needed. Unlocked mutexes consume no memory. 14 | // 15 | // The zero value is a valid MutexMap. 16 | type MutexMap[T comparable] struct { 17 | mu sync.Mutex 18 | locks map[T]*lockCtr 19 | } 20 | 21 | // lockCtr is used by Locker to represent a lock with a given key. 22 | type lockCtr struct { 23 | sync.Mutex 24 | waiters atomic.Int32 // Number of callers waiting to acquire the lock 25 | } 26 | 27 | var lockCtrPool = sync.Pool{New: func() any { return new(lockCtr) }} 28 | 29 | // Lock locks the mutex identified by key. 30 | func (l *MutexMap[T]) Lock(key T) { 31 | l.mu.Lock() 32 | if l.locks == nil { 33 | l.locks = make(map[T]*lockCtr) 34 | } 35 | 36 | nameLock, exists := l.locks[key] 37 | if !exists { 38 | nameLock = lockCtrPool.Get().(*lockCtr) 39 | l.locks[key] = nameLock 40 | } 41 | 42 | // Increment the nameLock waiters while inside the main mutex. 43 | // This makes sure that the lock isn't deleted if `Lock` and `Unlock` are called concurrently. 44 | nameLock.waiters.Add(1) 45 | l.mu.Unlock() 46 | 47 | // Lock the nameLock outside the main mutex so we don't block other operations. 48 | // Once locked then we can decrement the number of waiters for this lock. 49 | nameLock.Lock() 50 | nameLock.waiters.Add(-1) 51 | } 52 | 53 | // Unlock unlocks the mutex identified by key. 54 | // 55 | // It is a run-time error if the mutex is not locked on entry to Unlock. 56 | func (l *MutexMap[T]) Unlock(key T) { 57 | l.mu.Lock() 58 | defer l.mu.Unlock() 59 | nameLock, exists := l.locks[key] 60 | if !exists { 61 | // Generate an un-recover()-able error without reaching into runtime internals. 62 | (&sync.Mutex{}).Unlock() 63 | } 64 | 65 | if nameLock.waiters.Load() <= 0 { 66 | delete(l.locks, key) 67 | defer lockCtrPool.Put(nameLock) 68 | } 69 | nameLock.Unlock() 70 | } 71 | 72 | type nameLocker[T comparable] struct { 73 | l *MutexMap[T] 74 | key T 75 | } 76 | 77 | // Locker returns a [sync.Locker] interface that implements 78 | // the [sync.Locker.Lock] and [sync.Locker.Unlock] methods 79 | // by calling l.Lock(key) and l.Unlock(key). 80 | func (l *MutexMap[T]) Locker(key T) sync.Locker { 81 | return nameLocker[T]{l: l, key: key} 82 | } 83 | 84 | func (n nameLocker[T]) Lock() { 85 | n.l.Lock(n.key) 86 | } 87 | func (n nameLocker[T]) Unlock() { 88 | n.l.Unlock(n.key) 89 | } 90 | -------------------------------------------------------------------------------- /mutexmap_test.go: -------------------------------------------------------------------------------- 1 | package locker 2 | 3 | import ( 4 | "math/rand" 5 | "strconv" 6 | "sync" 7 | "testing" 8 | "time" 9 | ) 10 | 11 | func TestMutexMap_Lock(t *testing.T) { 12 | var l MutexMap[string] 13 | l.Lock("test") 14 | ctr := l.locks["test"] 15 | 16 | if w := ctr.waiters.Load(); w != 0 { 17 | t.Fatalf("expected waiters to be 0, got %d", w) 18 | } 19 | 20 | chDone := make(chan struct{}) 21 | go func() { 22 | l.Lock("test") 23 | close(chDone) 24 | }() 25 | 26 | chWaiting := make(chan struct{}) 27 | go func() { 28 | for range time.Tick(1 * time.Millisecond) { 29 | if ctr.waiters.Load() == 1 { 30 | close(chWaiting) 31 | break 32 | } 33 | } 34 | }() 35 | 36 | select { 37 | case <-chWaiting: 38 | case <-time.After(3 * time.Second): 39 | t.Fatal("timed out waiting for lock waiters to be incremented") 40 | } 41 | 42 | select { 43 | case <-chDone: 44 | t.Fatal("lock should not have returned while it was still held") 45 | default: 46 | } 47 | 48 | l.Unlock("test") 49 | 50 | select { 51 | case <-chDone: 52 | case <-time.After(3 * time.Second): 53 | t.Fatalf("lock should have completed") 54 | } 55 | 56 | if w := ctr.waiters.Load(); w != 0 { 57 | t.Fatalf("expected waiters to be 0, got %d", w) 58 | } 59 | } 60 | 61 | func TestMutexMap_Unlock(t *testing.T) { 62 | var l MutexMap[string] 63 | 64 | l.Lock("test") 65 | l.Unlock("test") 66 | 67 | chDone := make(chan struct{}) 68 | go func() { 69 | l.Lock("test") 70 | close(chDone) 71 | }() 72 | 73 | select { 74 | case <-chDone: 75 | case <-time.After(3 * time.Second): 76 | t.Fatalf("lock should not be blocked") 77 | } 78 | } 79 | 80 | func TestMutexMap_Concurrency(t *testing.T) { 81 | var l MutexMap[string] 82 | 83 | var wg sync.WaitGroup 84 | for i := 0; i <= 10000; i++ { 85 | wg.Add(1) 86 | go func() { 87 | l.Lock("test") 88 | // if there is a concurrency issue, will very likely panic here 89 | l.Unlock("test") 90 | wg.Done() 91 | }() 92 | } 93 | 94 | chDone := make(chan struct{}) 95 | go func() { 96 | wg.Wait() 97 | close(chDone) 98 | }() 99 | 100 | select { 101 | case <-chDone: 102 | case <-time.After(10 * time.Second): 103 | t.Fatal("timeout waiting for locks to complete") 104 | } 105 | 106 | // Since everything has unlocked this should not exist anymore 107 | if ctr, exists := l.locks["test"]; exists { 108 | t.Fatalf("lock should not exist: %v", ctr) 109 | } 110 | } 111 | 112 | func BenchmarkMutexMap(b *testing.B) { 113 | var l MutexMap[string] 114 | b.ReportAllocs() 115 | for i := 0; i < b.N; i++ { 116 | l.Lock("test") 117 | l.Lock(strconv.Itoa(i)) 118 | l.Unlock(strconv.Itoa(i)) 119 | l.Unlock("test") 120 | } 121 | } 122 | 123 | func BenchmarkMutexMap_Parallel(b *testing.B) { 124 | var l MutexMap[string] 125 | b.SetParallelism(128) 126 | b.RunParallel(func(pb *testing.PB) { 127 | for pb.Next() { 128 | l.Lock("test") 129 | l.Unlock("test") 130 | } 131 | }) 132 | } 133 | 134 | func BenchmarkMutexMap_MoreKeys(b *testing.B) { 135 | var l MutexMap[string] 136 | var keys []string 137 | for i := 0; i < 64; i++ { 138 | keys = append(keys, strconv.Itoa(i)) 139 | } 140 | b.SetParallelism(128) 141 | b.RunParallel(func(pb *testing.PB) { 142 | for pb.Next() { 143 | k := keys[rand.Intn(len(keys))] 144 | l.Lock(k) 145 | l.Unlock(k) 146 | } 147 | }) 148 | } 149 | -------------------------------------------------------------------------------- /rwmutexmap.go: -------------------------------------------------------------------------------- 1 | package locker 2 | 3 | import ( 4 | "sync" 5 | "sync/atomic" 6 | ) 7 | 8 | // RWMutexMap is a more convenient map[T]sync.RWMutex. It automatically makes 9 | // and deletes mutexes as needed. Unlocked mutexes consume no memory. 10 | // 11 | // The zero value is a valid MutexMap. 12 | type RWMutexMap[T comparable] struct { 13 | mu sync.Mutex 14 | locks map[T]*rwlockCtr 15 | } 16 | 17 | // rwlockCtr is used by RWLocker to represent a lock with a given key. 18 | type rwlockCtr struct { 19 | sync.RWMutex 20 | waiters atomic.Int32 // Number of callers waiting to acquire the lock 21 | readers atomic.Int32 // Number of readers currently holding the lock 22 | } 23 | 24 | var rwlockCtrPool = sync.Pool{New: func() any { return new(rwlockCtr) }} 25 | 26 | func (l *RWMutexMap[T]) get(key T) *rwlockCtr { 27 | if l.locks == nil { 28 | l.locks = make(map[T]*rwlockCtr) 29 | } 30 | 31 | nameLock, exists := l.locks[key] 32 | if !exists { 33 | nameLock = rwlockCtrPool.Get().(*rwlockCtr) 34 | l.locks[key] = nameLock 35 | } 36 | return nameLock 37 | } 38 | 39 | // Lock locks the RWMutex identified by key for writing. 40 | func (l *RWMutexMap[T]) Lock(key T) { 41 | l.mu.Lock() 42 | nameLock := l.get(key) 43 | 44 | // Increment the nameLock waiters while inside the main mutex. 45 | // This makes sure that the lock isn't deleted if `Lock` and `Unlock` are called concurrently. 46 | nameLock.waiters.Add(1) 47 | l.mu.Unlock() 48 | 49 | // Lock the nameLock outside the main mutex so we don't block other operations. 50 | // Once locked then we can decrement the number of waiters for this lock. 51 | nameLock.Lock() 52 | nameLock.waiters.Add(-1) 53 | } 54 | 55 | // RLock locks the RWMutex identified by key for reading. 56 | func (l *RWMutexMap[T]) RLock(key T) { 57 | l.mu.Lock() 58 | nameLock := l.get(key) 59 | 60 | nameLock.waiters.Add(1) 61 | l.mu.Unlock() 62 | 63 | nameLock.RLock() 64 | // Increment the number of readers before decrementing the waiters 65 | // so concurrent calls to RUnlock will not see a glitch where both 66 | // waiters and readers are 0. 67 | nameLock.readers.Add(1) 68 | nameLock.waiters.Add(-1) 69 | } 70 | 71 | // Unlock unlocks the RWMutex identified by key. 72 | // 73 | // It is a run-time error if the lock is not locked for writing on entry to Unlock. 74 | func (l *RWMutexMap[T]) Unlock(key T) { 75 | l.mu.Lock() 76 | defer l.mu.Unlock() 77 | nameLock := l.get(key) 78 | // We don't have to do anything special to handle the error case: 79 | // l.get(key) will return an unlocked mutex. 80 | 81 | if nameLock.waiters.Load() <= 0 && nameLock.readers.Load() <= 0 { 82 | delete(l.locks, key) 83 | defer rwlockCtrPool.Put(nameLock) 84 | } 85 | nameLock.Unlock() 86 | } 87 | 88 | // RUnlock unlocks the RWMutex identified by key for reading. 89 | // 90 | // It is a run-time error if the lock is not locked for reading on entry to RUnlock. 91 | func (l *RWMutexMap[T]) RUnlock(key T) { 92 | l.mu.Lock() 93 | defer l.mu.Unlock() 94 | nameLock := l.get(key) 95 | nameLock.readers.Add(-1) 96 | 97 | if nameLock.waiters.Load() <= 0 && nameLock.readers.Load() <= 0 { 98 | delete(l.locks, key) 99 | defer rwlockCtrPool.Put(nameLock) 100 | } 101 | nameLock.RUnlock() 102 | } 103 | 104 | // Locker returns a [sync.Locker] interface that implements 105 | // the [sync.Locker.Lock] and [sync.Locker.Unlock] methods 106 | // by calling l.Lock(name) and l.Unlock(name). 107 | func (l *RWMutexMap[T]) Locker(key T) sync.Locker { 108 | return nameRWLocker[T]{l: l, key: key} 109 | } 110 | 111 | // RLocker returns a [sync.Locker] interface that implements 112 | // the [sync.Locker.Lock] and [sync.Locker.Unlock] methods 113 | // by calling l.RLock(name) and l.RUnlock(name). 114 | func (l *RWMutexMap[T]) RLocker(key T) sync.Locker { 115 | return nameRLocker[T]{l: l, key: key} 116 | } 117 | 118 | type nameRWLocker[T comparable] struct { 119 | l *RWMutexMap[T] 120 | key T 121 | } 122 | type nameRLocker[T comparable] nameRWLocker[T] 123 | 124 | func (n nameRWLocker[T]) Lock() { 125 | n.l.Lock(n.key) 126 | } 127 | func (n nameRWLocker[T]) Unlock() { 128 | n.l.Unlock(n.key) 129 | } 130 | 131 | func (n nameRLocker[T]) Lock() { 132 | n.l.RLock(n.key) 133 | } 134 | func (n nameRLocker[T]) Unlock() { 135 | n.l.RUnlock(n.key) 136 | } 137 | -------------------------------------------------------------------------------- /rwmutexmap_test.go: -------------------------------------------------------------------------------- 1 | package locker 2 | 3 | import ( 4 | "math/rand" 5 | "strconv" 6 | "sync" 7 | "testing" 8 | "time" 9 | ) 10 | 11 | func TestRWMutex_Lock(t *testing.T) { 12 | var l RWMutexMap[string] 13 | l.Lock("test") 14 | ctr := l.locks["test"] 15 | 16 | if w := ctr.waiters.Load(); w != 0 { 17 | t.Fatalf("expected waiters to be 0, got %d", w) 18 | } 19 | 20 | chDone := make(chan struct{}) 21 | go func() { 22 | l.Lock("test") 23 | close(chDone) 24 | }() 25 | 26 | chWaiting := make(chan struct{}) 27 | go func() { 28 | for range time.Tick(1 * time.Millisecond) { 29 | if ctr.waiters.Load() == 1 { 30 | close(chWaiting) 31 | break 32 | } 33 | } 34 | }() 35 | 36 | select { 37 | case <-chWaiting: 38 | case <-time.After(3 * time.Second): 39 | t.Fatal("timed out waiting for lock waiters to be incremented") 40 | } 41 | 42 | select { 43 | case <-chDone: 44 | t.Fatal("lock should not have returned while it was still held") 45 | default: 46 | } 47 | 48 | l.Unlock("test") 49 | 50 | select { 51 | case <-chDone: 52 | case <-time.After(3 * time.Second): 53 | t.Fatalf("lock should have completed") 54 | } 55 | 56 | if w := ctr.waiters.Load(); w != 0 { 57 | t.Fatalf("expected waiters to be 0, got %d", w) 58 | } 59 | } 60 | 61 | func TestRWMutex_Unlock(t *testing.T) { 62 | var l RWMutexMap[string] 63 | 64 | l.Lock("test") 65 | l.Unlock("test") 66 | 67 | chDone := make(chan struct{}) 68 | go func() { 69 | l.Lock("test") 70 | close(chDone) 71 | }() 72 | 73 | select { 74 | case <-chDone: 75 | case <-time.After(3 * time.Second): 76 | t.Fatalf("lock should not be blocked") 77 | } 78 | } 79 | 80 | func TestRWMutex_RLock(t *testing.T) { 81 | var l RWMutexMap[string] 82 | rlocked := make(chan bool, 1) 83 | wlocked := make(chan bool, 1) 84 | n := 10 85 | 86 | go func() { 87 | for i := 0; i < n; i++ { 88 | l.RLock("test") 89 | l.RLock("test") 90 | rlocked <- true 91 | l.Lock("test") 92 | wlocked <- true 93 | } 94 | }() 95 | 96 | for i := 0; i < n; i++ { 97 | <-rlocked 98 | l.RUnlock("test") 99 | select { 100 | case <-wlocked: 101 | t.Fatal("RLock() didn't block Lock()") 102 | default: 103 | } 104 | l.RUnlock("test") 105 | <-wlocked 106 | select { 107 | case <-rlocked: 108 | t.Fatal("Lock() didn't block RLock()") 109 | default: 110 | } 111 | l.Unlock("test") 112 | } 113 | 114 | if len(l.locks) != 0 { 115 | t.Fatalf("expected no locks to be present in the map, got %d", len(l.locks)) 116 | } 117 | } 118 | 119 | func TestRWMutex_Concurrency(t *testing.T) { 120 | var l RWMutexMap[string] 121 | 122 | var wg sync.WaitGroup 123 | for i := 0; i <= 10000; i++ { 124 | wg.Add(1) 125 | go func() { 126 | l.Lock("test") 127 | // if there is a concurrency issue, will very likely panic here 128 | l.Unlock("test") 129 | l.RLock("test") 130 | l.RUnlock("test") 131 | wg.Done() 132 | }() 133 | } 134 | 135 | chDone := make(chan struct{}) 136 | go func() { 137 | wg.Wait() 138 | close(chDone) 139 | }() 140 | 141 | select { 142 | case <-chDone: 143 | case <-time.After(10 * time.Second): 144 | t.Fatal("timeout waiting for locks to complete") 145 | } 146 | 147 | // Since everything has unlocked this should not exist anymore 148 | if ctr, exists := l.locks["test"]; exists { 149 | t.Fatalf("lock should not exist: %v", ctr) 150 | } 151 | } 152 | 153 | func BenchmarkRWMutex(b *testing.B) { 154 | var l RWMutexMap[string] 155 | b.ReportAllocs() 156 | for i := 0; i < b.N; i++ { 157 | l.Lock("test") 158 | l.Lock(strconv.Itoa(i)) 159 | l.Unlock(strconv.Itoa(i)) 160 | l.Unlock("test") 161 | } 162 | } 163 | 164 | func BenchmarkRWMutex_Parallel(b *testing.B) { 165 | var l RWMutexMap[string] 166 | b.SetParallelism(128) 167 | b.RunParallel(func(pb *testing.PB) { 168 | for pb.Next() { 169 | l.Lock("test") 170 | l.Unlock("test") 171 | } 172 | }) 173 | } 174 | 175 | func BenchmarkRWMutex_MoreKeys(b *testing.B) { 176 | var l RWMutexMap[string] 177 | var keys []string 178 | for i := 0; i < 64; i++ { 179 | keys = append(keys, strconv.Itoa(i)) 180 | } 181 | b.SetParallelism(128) 182 | b.RunParallel(func(pb *testing.PB) { 183 | for pb.Next() { 184 | k := keys[rand.Intn(len(keys))] 185 | l.Lock(k) 186 | l.Unlock(k) 187 | } 188 | }) 189 | } 190 | --------------------------------------------------------------------------------