Skip to content

Instantly share code, notes, and snippets.

@syossan27
Created April 29, 2018 12:47
Show Gist options
  • Select an option

  • Save syossan27/bd90e646f19738ba605bc8606b01f576 to your computer and use it in GitHub Desktop.

Select an option

Save syossan27/bd90e646f19738ba605bc8606b01f576 to your computer and use it in GitHub Desktop.
package main
import (
"sync"
"fmt"
"sync/atomic"
)
var (
balance int32 = 100
wg = sync.WaitGroup{}
)
func main() {
// expect: balance = 55
var i int32
for i = 0; i < 10; i++ {
wg.Add(1)
go withdraw(i)
}
wg.Wait()
fmt.Println(balance)
}
func withdraw(amount int32) {
for {
if atomic.CompareAndSwapInt32(&balance, balance, balance - amount) {
break
}
}
wg.Done()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment