About
package main
import ( "fmt" "sync" )
var ( mutex sync.Mutex balance int )
func init() { balance = 1000 }
func deposit(value int, wg *sync.WaitGroup) { mutex.Lock() fmt.Printf("Depositing %d to account with balance: %d\n", value, balance) balance += value mutex.Unlock() wg.Done() }
func withdraw(value int, wg *sync.WaitGroup) { mutex.Lock() fmt.Printf("Withdrawing %d from account with balance: %d\n", value, balance) balance -= value mutex.Unlock() wg.Done() }
func main() { fmt.Println("Go Mutex Example")
var wg sync.WaitGroup
wg.Add(2)
go withdraw(700, &wg)
go deposit(500, &wg)
wg.Wait()
fmt.Printf("New Balance %d\n", balance)
}
package main import ( "fmt" ) func producer(ch chan<- int) { for i := 0; i < 10; i++ { ch <- i } close(ch) } func consumer(ch <-chan int, done chan<- bool) { for value := range ch { fmt.Println("Received:", value) } done <- true } func main() { ch := make(chan int) done := make(chan bool) go producer(ch) go consumer(ch, done) <-done }
package main
import
(
"fmt"
"sync"
"time"
)
func isEven(n int) bool {
return n%2 == 0
}
func main() {
n := 2
var m sync.Mutex
// now, both goroutines call m.Lock() before accessing `n`
// and call m.Unlock once they are done
go func() {
m.Lock()
defer m.Unlock()
nIsEven := isEven(n)
time.Sleep(5 * time.Millisecond)
if nIsEven {
fmt.Println(n, " is even")
return
}
fmt.Println(n, "is odd")
}()
go func() {
m.Lock()
n++
m.Unlock()
}()
time.Sleep(time.Second)
}
package main
import (
"fmt"
"sync"
)
var x = 0
func increment(wg sync.WaitGroup, m sync.Mutex) {
m.Lock()
x = x + 1
m.Unlock()
wg.Done()
}
func main() {
var w sync.WaitGroup
var m sync.Mutex
for i := 0; i < 500; i++ {
w.Add(1)
go increment(&w, &m)
}
w.Wait()
fmt.Println("final value of x", x)
}
package main
import "fmt"
// Functions func mul(a1, a2 int) int {
res := a1 * a2
fmt.Println("Result: ", res)
return 0
}
func show() { fmt.Println("Hello!, GeeksforGeeks") }
func main() {
mul(23, 45)
defer mul(23, 56)
show()
}