2024-05-06 20:40:05 +00:00
|
|
|
---
|
2024-10-30 17:04:36 +00:00
|
|
|
date: 20200918
|
2024-05-06 20:40:05 +00:00
|
|
|
id: 56a802e2-3871-4746-aec4-fa4bdae4d4fd
|
|
|
|
title: Golang Mutex
|
|
|
|
---
|
|
|
|
|
|
|
|
# Description
|
|
|
|
|
|
|
|
[Mutex](https://golang.org/pkg/sync/#Mutex) allows up to add locks to
|
|
|
|
our data so it can be accessed safely in a concurrent manner. While
|
|
|
|
locked other threads can't access the data. `Mutexes` should generally
|
|
|
|
be used for [managing
|
|
|
|
state](https://github.com/golang/go/wiki/MutexOrChannel).
|
|
|
|
|
|
|
|
# Syntax
|
|
|
|
|
|
|
|
``` go
|
|
|
|
type Counter struct {
|
|
|
|
mu sync.Mutex
|
|
|
|
value int
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Counter) Inc() {
|
|
|
|
c.mu.Lock()
|
|
|
|
defer c.mu.Unlock()
|
|
|
|
|
|
|
|
c.value++
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Counter) Value() int {
|
|
|
|
return c.value
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewCounter() *Counter {
|
|
|
|
return &Counter{}
|
|
|
|
}
|
|
|
|
```
|