Source file tour/concurrency/mutex-counter.go

     1  // +build OMIT
     2  
     3  package main
     4  
     5  import (
     6  	"fmt"
     7  	"sync"
     8  	"time"
     9  )
    10  
    11  // SafeCounter is safe to use concurrently.
    12  type SafeCounter struct {
    13  	mu sync.Mutex
    14  	v  map[string]int
    15  }
    16  
    17  // Inc increments the counter for the given key.
    18  func (c *SafeCounter) Inc(key string) {
    19  	c.mu.Lock()
    20  	// Lock so only one goroutine at a time can access the map c.v.
    21  	c.v[key]++
    22  	c.mu.Unlock()
    23  }
    24  
    25  // Value returns the current value of the counter for the given key.
    26  func (c *SafeCounter) Value(key string) int {
    27  	c.mu.Lock()
    28  	// Lock so only one goroutine at a time can access the map c.v.
    29  	defer c.mu.Unlock()
    30  	return c.v[key]
    31  }
    32  
    33  func main() {
    34  	c := SafeCounter{v: make(map[string]int)}
    35  	for i := 0; i < 1000; i++ {
    36  		go c.Inc("somekey")
    37  	}
    38  
    39  	time.Sleep(time.Second)
    40  	fmt.Println(c.Value("somekey"))
    41  }
    42  

View as plain text