Skip to content

Instantly share code, notes, and snippets.

@shemul
Created July 16, 2020 19:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shemul/d1549d144b800b3f776562d17aa9922f to your computer and use it in GitHub Desktop.
Save shemul/d1549d144b800b3f776562d17aa9922f to your computer and use it in GitHub Desktop.
Go Mutex
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