Last active
August 5, 2022 23:48
-
-
Save vhxs/cfe85694ffa9d2040f380128e423c164 to your computer and use it in GitHub Desktop.
Using CAS in golang
This file contains hidden or 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
// 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