Golang: Language: Concurrency: Synchronization

 1st September 2021 at 10:19am

Go 标准库并没有提供多线程(pthread)的接口。但 Go Runtime Scheduler 在调度 goroutine 时,是可能创建多个线程的,比如 goroutine 1 在执行 blocking I/O 时,go 必须创建新的线程来执行其他的 goroutine。

因此,在多个 goroutine 中访问共享的资源时,一样要考虑同步(synchronization)的问题。

Go 的 sync 包 提供了一些常见的设施:

  • Mutex:互斥锁,对应 pthread 中的 Mutex
  • RWMutex:读写锁,在 Mutex 基础上添加读写计数来实现
  • Cond:对应 pthread 中的 conditional variables
  • Once:对应 pthread_once()
  • Map:可以在多 goroutine 环境下不加锁使用的 map 结构(未了解其实现
  • Pool:未了解

同时参考 pthread 的 同步机制