var l sync. Mutexvar a stringfunc f () {a = "Hello, World" l.unlock ()}func main () {l.lock () go f () L.lock () print (a)}
The sync package implements two data types on the lock, sync. Mutex and sync. Rwmutex. [Mutex mutex is exclusive, can only lock once, unlock once, then can continue lock otherwise blocked. Read-write mutex reader-writer mutex is all reader sharing a lock or a writer exclusive a lock, if a reader lock to lock, other reader can lock but writer can't lock 。 ]
for sync. A Mutex or sync. For Rwmutex types of variable mutexes, assume n < m, for mutexes. The nth invocation of Unlock () is in the mutex. The first Call of Lock () occurs before the return of the M. [For a mutex, lock, the second lock will block, only unlock to continue lock, that's what it means. But what about unlock a mutex without lock? Error! ]
In fact, the key point is
After each lock is to wait for the return value of the Unclock, then how to ensure that the previous value of the unlock operation is returned, the go type defines that each lock must be after the last unlock to occur. So this is how the program reads:
1. Call a Lock2.gorou inside to assign a value, write operation, at this time unlock operation and write operation in the same "thread", and unlock after writing. 3. Call L.lock () to make sure that you must wait until the unlock is complete. That is, lock occurs after unclock, and more after assignment 4. The second lock takes place before print, so you know.
Interpretation of Go language lock