Skip to content

Instantly share code, notes, and snippets.

@kaipyroami
Created September 4, 2019 16:57
Show Gist options
  • Save kaipyroami/12423675f8895fd3a5231c89375fe2e3 to your computer and use it in GitHub Desktop.
Save kaipyroami/12423675f8895fd3a5231c89375fe2e3 to your computer and use it in GitHub Desktop.
An example of an atomic counter in Go.
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