You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

37 lines
944 B
Go

1 year ago
// A race condition occurs in this program because two goroutines are attempting
// to access a variable in shared memory `counter` concurrently.
// One would expect that the value of coutner at the end of the run would be
// 10,000 * 2 = 20,000 and on some runs it will produce this value. On other runs
// one gorountine will read the counter value just before the second goroutine
// writes to the shared variable. When the first goroutine writes it's counter value + 1
// it overwrites the counter value with an older value + 1. This results in some runs
// producing a counter result 1000s of values lower than expected.
package main
import (
"fmt"
"sync"
)
var counter int
func main() {
var wg sync.WaitGroup
wg.Add(2)
goroutine_count := 2
for i := 0; i < goroutine_count; i++ {
go func() {
for i := 0; i < 10000; i++ {
counter = counter + 1
}
wg.Done()
}()
}
wg.Wait()
fmt.Println("Counter:", counter)
}