| 153 | } |
| 154 | |
| 155 | func TestLockMultiRead(t *testing.T) { |
| 156 | t.Parallel() |
| 157 | |
| 158 | var waitGroup sync.WaitGroup |
| 159 | |
| 160 | var concurrentKey uint32 |
| 161 | |
| 162 | tempDir := t.TempDir() |
| 163 | |
| 164 | waitGroup.Add(3) |
| 165 | |
| 166 | // Start a readonly lock immediately |
| 167 | // Then wait 1s inside the lock - confirm the key got changed by the second read routine |
| 168 | go func() { |
| 169 | t.Log("Entering routine 1") |
| 170 | |
| 171 | defer waitGroup.Done() |
| 172 | |
| 173 | lErr := filesystem.WithReadOnlyLock(tempDir, func() error { |
| 174 | t.Log("Entering routine 1 read lock") |
| 175 | |
| 176 | atomic.StoreUint32(&concurrentKey, routine1) |
| 177 | |
| 178 | time.Sleep(1 * time.Second) |
| 179 | assert.Equal(t, atomic.LoadUint32(&concurrentKey), routine2) |
| 180 | |
| 181 | return nil |
| 182 | }) |
| 183 | |
| 184 | assert.NilError(t, lErr, "locking should not error") |
| 185 | }() |
| 186 | |
| 187 | // Wait 0.5s before locking, then change the key |
| 188 | go func() { |
| 189 | t.Log("Entering routine 2") |
| 190 | |
| 191 | defer waitGroup.Done() |
| 192 | |
| 193 | time.Sleep(500 * time.Millisecond) |
| 194 | |
| 195 | lErr := filesystem.WithReadOnlyLock(tempDir, func() error { |
| 196 | t.Log("Entering routine 2 read lock") |
| 197 | |
| 198 | atomic.StoreUint32(&concurrentKey, routine2) |
| 199 | |
| 200 | return nil |
| 201 | }) |
| 202 | |
| 203 | assert.NilError(t, lErr, "locking should not error") |
| 204 | }() |
| 205 | |
| 206 | time.Sleep(50 * time.Millisecond) |
| 207 | // Start a write lock, confirm we have waited for the read locks to finish, change the key |
| 208 | go func() { |
| 209 | t.Log("Entering routine 3") |
| 210 | |
| 211 | defer waitGroup.Done() |
| 212 | |