package main import ( "fmt" "sync" "time" ) // SafeCounter is safe to use concurrently. type SafeCounter struct { mu sync.Mutex v map[string]int } // Inc increments the counter for the given key. func (c *SafeCounter) Inc(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) Value(key string) int { c.mu.Lock() // Lock so only one goroutine at a time can access the map c.v. defer c.mu.Unlock() return c.v[key] } func main() { c := SafeCounter{v: make(map[string]int)} for i := 0; i < 1000; i++ { go c.Inc("somekey") } time.Sleep(time.Second) fmt.Println(c.Value("somekey")) } |
[링크 : https://go.dev/tour/concurrency/9]
func (*Mutex) Lock ¶ func (m *Mutex) Lock() Lock locks m. If the lock is already in use, the calling goroutine blocks until the mutex is available. func (*Mutex) TryLock ¶ added in go1.18 func (m *Mutex) TryLock() bool TryLock tries to lock m and reports whether it succeeded. Note that while correct uses of TryLock do exist, they are rare, and use of TryLock is often a sign of a deeper problem in a particular use of mutexes. func (*Mutex) Unlock ¶ func (m *Mutex) Unlock() Unlock unlocks m. It is a run-time error if m is not locked on entry to Unlock. A locked Mutex is not associated with a particular goroutine. It is allowed for one goroutine to lock a Mutex and then arrange for another goroutine to unlock it. |
[링크 : https://pkg.go.dev/sync#Mutex.Lock]
[링크 : https://mingrammer.com/gobyexample/mutexes/]
[링크 : https://www.joinc.co.kr/w/GoLang/example/mutexex]
[링크 : https://pyrasis.com/book/GoForTheReallyImpatient/Unit35]
'Programming > golang' 카테고리의 다른 글
golang switch, select (0) | 2023.05.16 |
---|---|
golang uds (0) | 2023.05.16 |
go 포맷터 (0) | 2023.05.11 |
golang echo directory listing (0) | 2023.05.08 |
golang websocket binary (0) | 2023.03.28 |