Skip to content

Instantly share code, notes, and snippets.

@kirugan
Last active February 21, 2018 16:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kirugan/118b862d068e2d0a5796b3bcaf34ea72 to your computer and use it in GitHub Desktop.
Save kirugan/118b862d068e2d0a5796b3bcaf34ea72 to your computer and use it in GitHub Desktop.
Example of non atomic ++
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)
}
@kirugan
Copy link
Author

kirugan commented Feb 21, 2018

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:

  1. First use mu.Lock() and mu.Unlock
  2. Second: optimize it by incrementing local variable first and at the end add this local value to the global one (and don't forget mutex!)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment