go-study/semaphore/semaphore_chan.go

26 lines
502 B
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package semaphore
import "sync"
type SemaChan struct {
sync.Locker
sem chan struct{} // 信号量通道
}
func NewSemaChan(n int) *SemaChan {
if n <= 0 {
n = 1 // 确保信号量至少为1直接变成一个互斥锁
}
return &SemaChan{
sem: make(chan struct{}, n), // 初始化信号量通道容量为n
}
}
func (s *SemaChan) Lock() {
<-s.sem // 使用接收的方式阻塞,用来与 sync.Mutex 的内存模型保持一致
}
func (s *SemaChan) Unlock() {
s.sem <- struct{}{}
}