|
1 | 1 | package mutexes
|
2 | 2 |
|
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "sync" |
| 6 | +) |
| 7 | + |
3 | 8 | // Allows for more complex state synchronisation
|
4 | 9 | // Across multiple goroutines where atomic/counters
|
5 | 10 | // are not enough.
|
6 |
| -func Run() {} |
| 11 | +func Run() { |
| 12 | + container := &Container{counters: map[string]int{"A": 0, "B": 0}} |
| 13 | + var wg sync.WaitGroup |
| 14 | + doIncrement := func(name string, n int) { |
| 15 | + for i := 0; i < n; i++ { |
| 16 | + container.Increment(name) |
| 17 | + } |
| 18 | + wg.Done() |
| 19 | + } |
| 20 | + wg.Add(5) |
| 21 | + go doIncrement("A", 10000) |
| 22 | + go doIncrement("B", 15000) |
| 23 | + go doIncrement("C", 5000) |
| 24 | + go doIncrement("A", 15000) |
| 25 | + go doIncrement("B", 25000) |
| 26 | + wg.Wait() |
| 27 | + fmt.Println(container.counters) |
| 28 | + container.CheckCounterIs("A", 25000) |
| 29 | + container.CheckCounterIs("B", 40000) |
| 30 | + container.CheckCounterIs("C", 5000) |
| 31 | + |
| 32 | +} |
| 33 | + |
| 34 | +// A simple type that stores counter hits. |
| 35 | +// Default state(s) of mutexes are usable. |
| 36 | +// Note: Mutexes should not be copied; so pass this by pointer. |
| 37 | +type Container struct { |
| 38 | + counters map[string]int |
| 39 | + mutex sync.Mutex |
| 40 | +} |
| 41 | + |
| 42 | +// Acquire the mutex lock and carry out the work. |
| 43 | +func (c *Container) Increment(counter string) { |
| 44 | + c.mutex.Lock() |
| 45 | + defer c.mutex.Unlock() |
| 46 | + c.counters[counter]++ |
| 47 | +} |
| 48 | + |
| 49 | +// Assert a counter (safely) has a particular value at a point in time. |
| 50 | +func (c *Container) CheckCounterIs(counter string, expected int) { |
| 51 | + c.mutex.Lock() |
| 52 | + defer c.mutex.Unlock() |
| 53 | + lookup, ok := c.counters[counter] |
| 54 | + if !ok { |
| 55 | + panic(fmt.Sprintf("Counter did not contain %s key.", counter)) |
| 56 | + } |
| 57 | + if lookup != expected { |
| 58 | + panic(fmt.Sprintf("Counter key %s was not equal to %d", counter, expected)) |
| 59 | + } |
| 60 | +} |
0 commit comments