Go Mutex Mutex

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Go mutex is a mutex, only lock and unlock two methods, the code between these two methods cannot be called simultaneously by multiple goroutins.

Look at the code:

Package main import ("FMT" "Sync" "Time") var m *sync. Mutex Func Main () {m = new (sync. Mutex) go lockprint (1) lockprint (2) time. Sleep (time. Second) fmt. Printf ("%s\n", "exit!")} Func lockprint (i int) {println (i, "lock start") M.lock () println (i, "in lock") time. Sleep (3 * time. Second) M.unlock () println (i, "Unlock")}

  

Interpretation:

The main function calls two times the Lockprint method, the println (i, "in lock") of this method, because it is between the lock and unlock of the mutex, so it is not possible to be executed again until the first call is not unlock.

Results:

2 Lock Start

2 in Lock

1 lock start

2 unlock

1 in lock

exit!

As can be seen from the above: after the second row of 2 in lock printing, 1 lock start has entered the call, but until 2 unlock after 1 in lock.

Ensures that the code between lock and unlock cannot be called simultaneously.

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.