Last active
February 21, 2018 16:37
-
-
Save kirugan/118b862d068e2d0a5796b3bcaf34ea72 to your computer and use it in GitHub Desktop.
Example of non atomic ++
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"time" | |
"sync" | |
) | |
var glob int64 = 0 | |
var mu sync.Mutex | |
func main() { | |
var wg sync.WaitGroup | |
for i := 0; i < 1000; i++ { | |
wg.Add(1) | |
go func (wg *sync.WaitGroup) { | |
time.Sleep(200 * time.Millisecond) | |
for j := 0; j < 1000; j++ { | |
// mu.Lock() | |
glob++ | |
// mu.Unlock() | |
} | |
wg.Done() | |
} (&wg) | |
} | |
wg.Wait() | |
fmt.Println("I = " , glob) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
We expect that I = 1 000 000, but it's not determined cause ++ is not atomic (i'll add a link to the post which describes why).
How to improve this: