Created
July 16, 2020 19:26
-
-
Save shemul/d1549d144b800b3f776562d17aa9922f to your computer and use it in GitHub Desktop.
Go Mutex
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
package main | |
import ( | |
"fmt" | |
"sync" | |
) | |
var ( | |
mutex = sync.Mutex{} | |
balance int | |
) | |
func main() { | |
balance= 1000 | |
fmt.Println("hello") | |
var wg sync.WaitGroup | |
wg.Add(2) | |
go widraw(700 , &wg) | |
go deposit(500 , &wg) | |
wg.Wait() | |
fmt.Printf("final balance %d\n" , balance) | |
} | |
func widraw(i int , wg *sync.WaitGroup) { | |
mutex.Lock() | |
fmt.Printf("witdrawing amount %d from balance %d\n" , i , balance) | |
balance -= i | |
mutex.Unlock() | |
wg.Done() | |
} | |
func deposit(i int , wg *sync.WaitGroup) { | |
mutex.Lock() | |
fmt.Printf("depositing amount %d from balanncce %d\n" , i , balance) | |
balance += i | |
mutex.Unlock() | |
wg.Done() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment