Skip to content

Instantly share code, notes, and snippets.

@oNddleo
Created June 26, 2023 09:39
Show Gist options
  • Save oNddleo/0af97d9338a1d07fe383bf7d41128468 to your computer and use it in GitHub Desktop.
Save oNddleo/0af97d9338a1d07fe383bf7d41128468 to your computer and use it in GitHub Desktop.
Race Condition With Bank Deposit and Withdraw Example
package main
import (
"fmt"
"sync"
)
var (
balance int
)
func init() {
balance = 100
}
func deposit(val int, wg *sync.WaitGroup, ch chan bool) {
ch <- true
balance += val
<-ch
wg.Done()
}
func withdraw(val int, wg *sync.WaitGroup, ch chan bool) {
ch <- true
balance -= val
<-ch
wg.Done()
}
func main() {
var wg sync.WaitGroup
ch := make(chan bool, 1) // create the channel
wg.Add(3)
go deposit(20, &wg, ch)
go withdraw(80, &wg, ch)
go deposit(40, &wg, ch)
wg.Wait()
fmt.Printf("Balance is: %d\n", balance)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment