// 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) }