golang ----- sync

1, mutex Mutex

Mutex Mutex is, Lock () locked, the Unlock () unlock code between these two methods can not be simultaneously a plurality of calls to goroutins.
After a goroutine get Mutex, we can only wait until the other goroutine goroutine release the Mutex
use Lock () after the lock can no longer continue its locked, until after using the Unlock () to unlock the lock again
at Lock () before use unlock () will cause panic anomaly
has been locked Mutex is not associated with a particular goroutine, so you can use a goroutine its lock, and then use other goroutine unlock it
before in the same goroutine Mutex unlock the lock again be It will lead to a deadlock
suitable for reading and writing uncertain, and only one read or write scenes

2, read and write mutex RWMutex

The lock can be held simultaneously by a plurality of read or write the only one who holds.

WMutex is a Write Once Read Many lock that locks you can add multiple read or a write lock
case of a read lock occupied will stop writing, I will not stop reading, you can get more goroutine lock simultaneously for reading and writing locks will prevent other goroutine (regardless of read and write) came from this whole lock goroutine exclusively
applicable to read how much of the writing scene

Lock() 和 Unlock()

Lock () write-lock, Unlock () solution write lock
if you already have other read and write locks before write-lock, Lock () will block until the lock is available, to ensure that the lock is available, it has been blocked Lock () call will be excluded from the new reader locks obtained by writing a lock permissions higher than a read lock, write lock priority write lock
() before using Unlock the lock () will cause panic abnormalities

RLock () and RUnlock ()

RLock () plus read lock, RUnlock () Interpretation lock
RLock () when adding a read lock, if there is a write lock, you can not add a read lock; when only write lock or no lock, you can add read locks, read locks can load multiple a
RUnlock () reading lock, RUnlock () revoke word RLock () call, while other existing read lock is not effective
call RUnlock without a read lock case () will cause panic error
RUnlock () number shall not be redundant RLock (), otherwise it will cause panic error

Published 27 original articles · won praise 1 · views 1205

Guess you like

Origin blog.csdn.net/qq_40484416/article/details/103536580