diff --git a/main.go b/main.go index 0f9267a..d162de8 100644 --- a/main.go +++ b/main.go @@ -15,7 +15,8 @@ package main // import "git.sangeeth.dev/gobyexample/workerpools" // import "git.sangeeth.dev/gobyexample/waitgroups" // 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() { // runes.Runes() @@ -33,5 +34,6 @@ func main() { // workerpools.WorkerPools() // waitgroups.WaitGroups() // ratelimiting.RateLimiting() - atomics.Atomics() + // atomics.Atomics() + mutex.Mutex() } diff --git a/mutex/mutex.go b/mutex/mutex.go new file mode 100644 index 0000000..79b11de --- /dev/null +++ b/mutex/mutex.go @@ -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) +}