Created
June 26, 2023 09:39
-
-
Save oNddleo/0af97d9338a1d07fe383bf7d41128468 to your computer and use it in GitHub Desktop.
Race Condition With Bank Deposit and Withdraw Example
This file contains 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
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