Golang Standard library Depth-lock, semaphore (sync)

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

Overview

The Sync package provides basic synchronization primitives, such as mutex locks. In addition to the once and waitgroup types, most are suitable for low-level program threads, with high levels of synchronization using channel communication better.

The value of the type of this package should not be copied.

Although the document interpretation may not be deep enough or easy to understand, I think it might be better to stick it out and compare it.

It is easy to implement concurrency in the go language or to create a goroutine simply by adding "go" in front of the function, so how can synchronization and communication between multiple goroutine be implemented in concurrency? A: Channel I was the first to think of, sync, atomic operation Atomic and so on.

First, let's introduce the various types under the sync package. So let's start by listing all the types under the Sync pack.

1. Cond Condition Waiting

type Cond struct {        // L is held while observing or changing the condition        L Locker        // contains filtered or unexported fields}

Explain:

COND implements a conditional variable, where a thread is assembled to wait for a thread or to announce the occurrence of an event.

Each cond instance has a related lock (typically a value of type *mutex or *rwmutex) that must remain locked when the condition is changed or when the wait method is called. Cond can be created as a field for other structures, andcond cannot be copied after it is started.

The condition waits for the routine to wait through wait, allowing a waiting routine to continue through the signal, allowing all waiting to continue through broadcase.

You need to lock the C.L manually before wait, and wait ends the manual unlock. In order to avoid false wakes, you need to put the wait in a loop of conditional judgment, which is officially required:

c.L.Lock()for !condition() {    c.Wait()}// 执行条件满足之后的动作...c.L.Unlock()

Member Documents:

type Cond struct {    L Locker // 在“检查条件”或“更改条件”时 L 应该锁定。} // 创建一个条件等待func NewCond(l Locker) *Cond// Broadcast 唤醒所有等待的 Wait,建议在“更改条件”时锁定 c.L,更改完毕再解锁。func (c *Cond) Broadcast()// Signal 唤醒一个等待的 Wait,建议在“更改条件”时锁定 c.L,更改完毕再解锁。func (c *Cond) Signal()// Wait 会解锁 c.L 并进入等待状态,在被唤醒时,会重新锁定 c.Lfunc (c *Cond) Wait()

code example:

package mainimport ("fmt""sync""time")func main() {condition := false // 条件不满足var mu sync.Mutexcond := sync.NewCond(&mu) // 创建一个Cond//让协程去创造条件go func() {mu.Lock()condition = true // 改写条件time.Sleep(3 * time.Second)cond.Signal() // 发送通知:条件okmu.Unlock()}()mu.Lock()// 检查条件是否满足,避免虚假通知,同时避免 Signal 提前于 Wait 执行。for !condition { // 如果Signal提前执行了,那么此处就是false了// 等待条件满足的通知,如果虚假通知,则继续循环等待cond.Wait() // 等待时 mu 处于解锁状态,唤醒时重新锁定。 (阻塞当前线程)}fmt.Println("条件满足,开始后续动作...")mu.Unlock()}

2. Locker

type Locker interface {    Lock()    Unlock()}

The locker interface represents an object that can be locked and unlocked. is an interface .

3. Mutex Mutex

type Mutex struct {    // contains filtered or unexported fields}

Explain:

Mutexes are mutex locks. The 0 value of a mutex is a unlocked mutex. The Mutex must not be copied after the first use .

Mutexes are used to guarantee that only one routine can access an object at any one time. The initial value of the mutex is the unlocked state. It is usually used as your name field for other structs and can be used in parallel in multiple routines safely.

Member Documents:

// Lock 用于锁住 m,如果 m 已经被加锁,则 Lock 将被阻塞,直到 m 被解锁。func (m *Mutex) Lock()// Unlock 用于解锁 m,如果 m 未加锁,则该操作会引发 panic。func (m *Mutex) Unlock()

code example:

package mainimport ("fmt""sync")type SafeInt struct {sync.MutexNum int}func main() {waitNum := 10 // 设置等待的个数(继续往下看)count := SafeInt{}done := make(chan bool)for i := 0; i < waitNum; i++ {go func(i int) {count.Lock() // 加锁,防止其它例程修改 countcount.Num = count.Num + ifmt.Print(count.Num, " ")count.Unlock()done <- true}(i)}for i := 0; i < waitNum; i++ {<-done}}

[' Go run Sync_mutex.go ' | done:216.47974ms]
1 4 8 8 10 15 21 30 37 45

Note: Multiple output results are inconsistent, imagine why there are 10 results in 0 worth, why 10 of the results are greater than 0? Or is it more than 1? So will there be 10 results in the minimum value is 9?

4. Once One-time execution

type Once struct {    // contains filtered or unexported fields}

Explain:

A once is an object that performs only one action at a time.

Once function is called multiple times, but only once , Once only one method, Once.do (), to do pass a function, this function in the first execution of Once.do () will be called, and then execute once.do () will not have any action, even if other functions are passed in, they will not be executed , and a Once object needs to be recreated if other functions are to be executed.

Member Documents:

// 多次调用仅执行一次指定的函数 ffunc (o *Once) Do(f func())

code example:

package main// 官方案例import ("fmt""sync")func main() {var once sync.Oncevar num intonceBody := func() {fmt.Println("Only once")}done := make(chan bool)for i := 0; i < 10; i++ {go func() {once.Do(onceBody) // 多次调用done <- true}()}for i := 0; i < 10; i++ {<-done}}

Cond...

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.