| 80 | } |
| 81 | |
| 82 | func TestLockWriteConcurrent(t *testing.T) { |
| 83 | t.Parallel() |
| 84 | |
| 85 | var waitGroup sync.WaitGroup |
| 86 | |
| 87 | var concurrentKey uint32 |
| 88 | |
| 89 | tempDir := t.TempDir() |
| 90 | |
| 91 | waitGroup.Add(2) |
| 92 | |
| 93 | // Start a lock, set the key, sleep 1s and confirm the key is still the same |
| 94 | go func() { |
| 95 | defer waitGroup.Done() |
| 96 | |
| 97 | lErr := filesystem.WithLock(tempDir, func() error { |
| 98 | atomic.StoreUint32(&concurrentKey, routine1) |
| 99 | |
| 100 | time.Sleep(1 * time.Second) |
| 101 | assert.Equal(t, atomic.LoadUint32(&concurrentKey), routine1) |
| 102 | |
| 103 | return nil |
| 104 | }) |
| 105 | |
| 106 | assert.NilError(t, lErr, "locking should not error") |
| 107 | }() |
| 108 | |
| 109 | // Wait 0.5s, start another lock, set the key, sleep 1s and confirm the key is still the same |
| 110 | go func() { |
| 111 | defer waitGroup.Done() |
| 112 | |
| 113 | time.Sleep(500 * time.Millisecond) |
| 114 | |
| 115 | lErr := filesystem.WithLock(tempDir, func() error { |
| 116 | atomic.StoreUint32(&concurrentKey, routine2) |
| 117 | |
| 118 | time.Sleep(1 * time.Second) |
| 119 | assert.Equal(t, atomic.LoadUint32(&concurrentKey), routine2) |
| 120 | |
| 121 | return nil |
| 122 | }) |
| 123 | |
| 124 | assert.NilError(t, lErr, "locking should not error") |
| 125 | }() |
| 126 | |
| 127 | // Start a lock, set the key, wait 1s, confirm the key is still the same |
| 128 | lErr := filesystem.WithLock(tempDir, func() error { |
| 129 | atomic.StoreUint32(&concurrentKey, mainroutine1) |
| 130 | |
| 131 | time.Sleep(1 * time.Second) |
| 132 | assert.Equal(t, atomic.LoadUint32(&concurrentKey), mainroutine1) |
| 133 | |
| 134 | return nil |
| 135 | }) |
| 136 | assert.NilError(t, lErr, "locking should not error") |
| 137 | |
| 138 | // Wait 0.75s, start a lock, set the key, sleep 1s, confirm the key is unchanged |
| 139 | time.Sleep(750 * time.Millisecond) |