【Golang】使用 - sync.RWMutex

Posted by 西维蜀黍 on 2021-07-19, Last Modified on 2021-09-21
package main

import (
	"sync"
)

// SafeCounter is safe to use concurrently.
type SafeCounter struct {
	mu sync.RWMutex
	v  map[string]int
}

// Inc increments the counter for the given key.
func (c *SafeCounter) Write(key string) {
	c.mu.Lock()
	// Lock so only one goroutine at a time can access the map c.v.
	c.v[key]++
	c.mu.Unlock()
}

// Value returns the current value of the counter for the given key.
func (c *SafeCounter) Read(key string) int {
	c.mu.RLock()
	defer c.mu.RUnlock()
	return c.v[key]
}

func main() {
	c := SafeCounter{v: make(map[string]int)}
	go func() {
		for {
			_ = c.Read("test")
		}
	}()
	go func() {
		for {
			c.Write("test")
		}
	}()
	select {}
}

Reference


TOC