a mutex is a mutex that can be created as a field for other structures, and a value of 0 is the unlocked state. The lock of the Mutex type is not thread-independent, and can be loads and unlocked by different lines.
Method
Func (*mutex) Lock
func (m *Mutex) Lock()
The Lock method locks m, and if M is already locked, it blocks until M unlocks.
Func (*mutex) Unlock
func (m *Mutex) Unlock()
The Unlock method unlocks m, which causes a run-time error if M is not locked.
Attention
- After a goroutine obtains the mutex, the other goroutine can only wait until the Goroutine releases the mutex
After using lock (), you can no longer lock it until you unlock it with Unlock ().
- Using Unlock () before Lock () causes panic exceptions
- A locked Mutex is not associated with a specific goroutine, so it can be locked with one goroutine and then unlocked with another goroutine
- Lock again before the Mutex in the same goroutine is unlocked, causing a deadlock
- For read-write uncertainties, and only one read or write scenario
Instance
package mainimport ( "fmt" "sync" "time")func main() { var mutex sync.Mutex wait := sync.WaitGroup{} fmt.Println("Locked") mutex.Lock() for i := 1; i <= 3; i++ { wait.Add(1) go func(i int) { fmt.Println("Not lock:", i) mutex.Lock() fmt.Println("Lock:", i) time.Sleep(time.Second) fmt.Println("Unlock:", i) mutex.Unlock() defer wait.Done() }(i) } time.Sleep(time.Second) fmt.Println("Unlocked") mutex.Unlock() wait.Wait()}
Operation Result:
LockedNot lock: 1Not lock: 2Not lock: 3UnlockedLock: 1Unlock: 1Lock: 2Unlock: 2Lock: 3Unlock: 3
Reference
- Standard library document--sync. Mutex
- Golang in sync. Mutex and sync. Rwmutex
Original address: Https://shockerli.net/post/go
...