Skip to content

Instantly share code, notes, and snippets.

@vhxs
Last active August 5, 2022 23:48
Show Gist options
  • Save vhxs/cfe85694ffa9d2040f380128e423c164 to your computer and use it in GitHub Desktop.
Save vhxs/cfe85694ffa9d2040f380128e423c164 to your computer and use it in GitHub Desktop.
Using CAS in golang
// Using compare-and-swap synchronization primitive to atomically update a shared counter
package main
import (
"fmt"
"sync"
"sync/atomic"
)
func main() {
var counter = int64(0)
var wg sync.WaitGroup
for id := 0; id < 16; id++ {
wg.Add(1)
go func () {
defer wg.Done()
var success = false
var updatedCounter int64
var readCounter int64
for !success {
readCounter = counter
updatedCounter = readCounter + 1
success = atomic.CompareAndSwapInt64(&counter, readCounter, updatedCounter)
}
}()
}
wg.Wait()
fmt.Println(counter)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment