From c93e7c1cf8287fe2cee40ba5b4fd2829bc91db6c Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Mon, 22 Nov 2021 12:53:10 -0800 Subject: [PATCH] Generate public/* for mutex --- examples/mutexes/mutexes.go | 2 +- examples/mutexes/mutexes.hash | 4 ++-- public/mutexes | 35 ++++++++++++++++++++++------------- 3 files changed, 25 insertions(+), 16 deletions(-) diff --git a/examples/mutexes/mutexes.go b/examples/mutexes/mutexes.go index 0a34010..448eb6c 100644 --- a/examples/mutexes/mutexes.go +++ b/examples/mutexes/mutexes.go @@ -17,7 +17,7 @@ import ( // `struct` is passed around, it should be done by // pointer. type Container struct { - mu sync.Mutex + mu sync.Mutex counters map[string]int } diff --git a/examples/mutexes/mutexes.hash b/examples/mutexes/mutexes.hash index 70c6f65..974d727 100644 --- a/examples/mutexes/mutexes.hash +++ b/examples/mutexes/mutexes.hash @@ -1,2 +1,2 @@ -07179e54fb3466ab01ac8aa9550feb213a206785 -i50fhu4l-n0 +3688453f408d8c7cc6db91ab7fd5e0ac06ade7ea +tDqeib2-yZA diff --git a/public/mutexes b/public/mutexes index 4fd5e95..9abb3ad 100644 --- a/public/mutexes +++ b/public/mutexes @@ -44,7 +44,7 @@ to safely access data across multiple goroutines.

- +
package main
 
@@ -68,8 +68,7 @@ to safely access data across multiple goroutines.

Container holds a map of counters; since we want to update it concurrently from multiple goroutines, we -add a Mutex to synchronize access. The mutex is -embedded in this struct; this is idiomatic in Go. +add a Mutex to synchronize access. Note that mutexes must not be copied, so if this struct is passed around, it should be done by pointer.

@@ -79,7 +78,7 @@ pointer.

 type Container struct {
-    sync.Mutex
+    mu       sync.Mutex
     counters map[string]int
 }
 
@@ -90,9 +89,7 @@ pointer.

Lock the mutex before accessing counters; unlock it at the end of the function using a defer -statement. Since the mutex is embedded into -Container, we can call the mutex’s methods like -Lock directly on c.

+statement.

@@ -108,23 +105,35 @@ statement. Since the mutex is embedded into -
    c.Lock()
-    defer c.Unlock()
+          
    c.mu.Lock()
+    defer c.mu.Unlock()
     c.counters[name]++
 }
 
+ + +

Note that the zero value of a mutex is usable as-is, so no +initialization is required here.

+ + + + +
func main() {
+    c := Container{
+
+ + + -
func main() {
-    c := Container{
-        counters: map[string]int{"a": 0, "b": 0},
+          
        counters: map[string]int{"a": 0, "b": 0},
     }
 
@@ -238,7 +247,7 @@ management task using only goroutines and channels.