Add mutex
This commit is contained in:
parent
c23e699122
commit
58ffd80d36
6
main.go
6
main.go
@ -15,7 +15,8 @@ package main
|
|||||||
// import "git.sangeeth.dev/gobyexample/workerpools"
|
// import "git.sangeeth.dev/gobyexample/workerpools"
|
||||||
// import "git.sangeeth.dev/gobyexample/waitgroups"
|
// import "git.sangeeth.dev/gobyexample/waitgroups"
|
||||||
// import "git.sangeeth.dev/gobyexample/ratelimiting"
|
// import "git.sangeeth.dev/gobyexample/ratelimiting"
|
||||||
import "git.sangeeth.dev/gobyexample/atomics"
|
// import "git.sangeeth.dev/gobyexample/atomics"
|
||||||
|
import "git.sangeeth.dev/gobyexample/mutex"
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
// runes.Runes()
|
// runes.Runes()
|
||||||
@ -33,5 +34,6 @@ func main() {
|
|||||||
// workerpools.WorkerPools()
|
// workerpools.WorkerPools()
|
||||||
// waitgroups.WaitGroups()
|
// waitgroups.WaitGroups()
|
||||||
// ratelimiting.RateLimiting()
|
// ratelimiting.RateLimiting()
|
||||||
atomics.Atomics()
|
// atomics.Atomics()
|
||||||
|
mutex.Mutex()
|
||||||
}
|
}
|
||||||
|
44
mutex/mutex.go
Normal file
44
mutex/mutex.go
Normal file
@ -0,0 +1,44 @@
|
|||||||
|
package mutex
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
type container struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
counter map[string]int
|
||||||
|
}
|
||||||
|
|
||||||
|
func Mutex() {
|
||||||
|
var wg sync.WaitGroup
|
||||||
|
c := container{
|
||||||
|
counter: map[string]int{
|
||||||
|
"a": 0,
|
||||||
|
"b": 0,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
increment := func(key string, times uint) {
|
||||||
|
c.mu.Lock()
|
||||||
|
defer c.mu.Unlock()
|
||||||
|
|
||||||
|
time.Sleep(200 * time.Millisecond)
|
||||||
|
|
||||||
|
for range times {
|
||||||
|
c.counter[key]++
|
||||||
|
}
|
||||||
|
|
||||||
|
wg.Done()
|
||||||
|
}
|
||||||
|
|
||||||
|
wg.Add(3)
|
||||||
|
go increment("a", 1000)
|
||||||
|
go increment("b", 1000)
|
||||||
|
go increment("a", 1000)
|
||||||
|
|
||||||
|
wg.Wait()
|
||||||
|
|
||||||
|
fmt.Printf("counter after all increment() calls: %v\n", c.counter)
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user