1

Golang | 同步与锁

 2 years ago
source link: https://ijayer.github.io/post/tech/code/golang/20170608-go-sync-and-mutex/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Mutex

互斥锁是传统的并发程序对共享资源进行访问控制的主要手段。

sync.Mutex 是一个互斥锁,其作用是守护在临界区入口来保证同一时间只有一个线程进入临界区。其在sync中的定义和方法:

  • type Mutex struct{}
  • func (m *Mutex) Lock()
  • func (m *Mutex) Unlock()

适用于读写不确定场景,即读写次数没有明显的区别,并且允许只有一个读或者写的场景,所以该锁叶叫做全局锁.

RWMutex

sync.RWMutex 是针对读写操作的互斥锁。其遵循两个原则:

  • 可以随便的读,并且可以有多个goroutine同时进行读
  • 写的时候,其他协程既不能读也不能写

RWMutex提供了四个方法:

  • 读操作的锁定与解锁

    • func (rw *RWMutex) RLock()
    • func (rw *RWMutex) RUnlock()
  • 写操作的锁定与解锁

    • func (rw *RWMutex) Lock()
    • func (rw *RWMutex) Unlock()

经常用于读次数远远多于写次数的场景.

sync.Once 只会执行一次,其方法为:

  • func (o *Once) Do(f func())

WaitGroup

sync.WaitGroup:一个 WaitGroup 会等待一个 goroutines 集合执行结束。

怎么用呢?

在main goroutine里面调用Add方法设置需要等待的goroutines数量,然后每运行一个goroutine, 且在其结束的时候调用Done方法减少一个goroutine。main goroutine会阻塞直到添加的goroutines执行完毕。其实现的方法如下:

  • func (wg *WaitGroup) Add(delta int) // 添加等待的goroutine数量(delta)
  • func (wg *WaitGroup) Done() // 减掉一个goroutine, <=> Add(-1)
  • func (wg *WaitGroup) Wait() // 执行阻塞,直到所有的WaitGroup数量变成0

See Also

Thanks to the authors 🙂


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK