Created
September 4, 2019 16:57
-
-
Save kaipyroami/12423675f8895fd3a5231c89375fe2e3 to your computer and use it in GitHub Desktop.
An example of an atomic counter in Go.
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" | |
"sync" | |
"sync/atomic" | |
) | |
func main() { | |
var wg sync.WaitGroup | |
var c int64 = 0 | |
wg.Add(100) | |
for i := 0; i < 100; i++ { | |
go func() { | |
var count int64 | |
count = c | |
atomic.AddInt64(&count, 1) | |
c = count | |
fmt.Println(c) | |
wg.Done() | |
}() | |
} | |
wg.Wait() | |
fmt.Println("End value: ", c) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment