-
Notifications
You must be signed in to change notification settings - Fork 0
/
race_test.go
38 lines (29 loc) · 731 Bytes
/
race_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package problems
// Race Conditions: concurrent threads changing shared data without sufficient protection mechanisms.
import (
"testing"
)
const concurrency = 1000
// shared memory
var value = 0
// change the value of unprotected shared memory
func increment(done chan bool) {
value++
done <- true
}
func Test_RaceCondition(t *testing.T) {
done := make(chan bool, concurrency)
// start N go routines
for i := 0; i < concurrency; i++ {
go increment(done)
}
// wait for all go routines to finish
for i := 0; i < concurrency; i++ {
<-done
}
// assert that writes were lost due to race conditions
if value != concurrency {
t.Logf("expected value to be: %v but was: %v", concurrency, value)
t.Fatal()
}
}