Interpretation of Go language lock

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.