Go Standard library--sync. Mutex Mutex

Source: Internet
Author: User
a mutex is a mutex that can be created as a field for other structures, and a value of 0 is the unlocked state. The lock of the Mutex type is not thread-independent, and can be loads and unlocked by different lines.

Method

Func (*mutex) Lock

func (m *Mutex) Lock()

The Lock method locks m, and if M is already locked, it blocks until M unlocks.

Func (*mutex) Unlock

func (m *Mutex) Unlock()

The Unlock method unlocks m, which causes a run-time error if M is not locked.

Attention

    • After a goroutine obtains the mutex, the other goroutine can only wait until the Goroutine releases the mutex

After using lock (), you can no longer lock it until you unlock it with Unlock ().

    • Using Unlock () before Lock () causes panic exceptions
    • A locked Mutex is not associated with a specific goroutine, so it can be locked with one goroutine and then unlocked with another goroutine
    • Lock again before the Mutex in the same goroutine is unlocked, causing a deadlock
    • For read-write uncertainties, and only one read or write scenario

Instance

package mainimport (    "fmt"    "sync"    "time")func main() {    var mutex sync.Mutex    wait := sync.WaitGroup{}    fmt.Println("Locked")    mutex.Lock()    for i := 1; i <= 3; i++ {        wait.Add(1)        go func(i int) {            fmt.Println("Not lock:", i)            mutex.Lock()            fmt.Println("Lock:", i)            time.Sleep(time.Second)            fmt.Println("Unlock:", i)            mutex.Unlock()            defer wait.Done()        }(i)    }    time.Sleep(time.Second)    fmt.Println("Unlocked")    mutex.Unlock()    wait.Wait()}

Operation Result:

LockedNot lock: 1Not lock: 2Not lock: 3UnlockedLock: 1Unlock: 1Lock: 2Unlock: 2Lock: 3Unlock: 3

Reference

    • Standard library document--sync. Mutex
    • Golang in sync. Mutex and sync. Rwmutex
Original address: Https://shockerli.net/post/go
...
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.