Golang Sync Mutex Mutex

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

Golang multithreading is easy to use, but sometimes you need to lock the data to prevent data from being changed by other threads. Then the mutex under the sync package is very useful.

A mutex is a mutex. Can be part of a struct so that the struct prevents the data from being changed by multithreading.

Here's an example:

Package Mainimport ("FMT" "Sync" "Time") type User struct {Name   stringlocker *sync. Mutex}func (U *user) SetName (Wati *sync. Waitgroup, name string) {defer func () {fmt. Println ("Unlock Set Name:", name) U.locker.unlock () Wati. Done ()} () U.locker.lock () fmt. Println ("Lock Set Name:", name) time. Sleep (1 * time. Second) u.name = Name}func (u *user) GetName (Wati *sync. Waitgroup) {defer func () {fmt. Println ("Unlock Get Name:", U.name) U.locker.unlock () Wati. Done ()} () U.locker.lock () fmt. Println ("Lock Get Name:", U.name) time. Sleep (1 * time. Second)}func Main () {User: = User{}user. Locker = new (sync. Mutex) Wait: = &sync. Waitgroup{}names: = []string{"A", "B", "C"}for _, Name: = range names {wait. ADD (2) Go user. SetName (wait, name) go user. GetName (Wait)}wait. Wait ()}
Output Result:

Lock set Name:aunlock set Name:alock get Name:aunlock get Name:alock set Name:bunlock set Name:block get Name:bunlo CK get Name:block Set Name:cunlock set Name:clock get Name:cunlock get Name:c

The program is simple enough to prevent other threads from changing when the name is being read. There are some problems with this program, but in all cases, it is intended to demonstrate the purpose of the mutex. Allows a struct to be manipulated by only one thread, while the other threads will block.

Article from: http://www.liguosong.com/2014/05/07/golang-sync-mutex/

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.