3 Star 14 Fork 4

赵春/fabric-gm

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
semaphore.go 1.26 KB
一键复制 编辑 原始数据 按行查看 历史
赵春 提交于 2022-02-22 14:31 . 基础版本作成
/*
Copyright IBM Corp. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
// Package semaphore provides an implementation of a counting semaphore.
package semaphore
import (
"context"
)
// Semaphore is a buffered channel based implementation of a counting
// semaphore.
type Semaphore chan struct{}
// New creates a Semaphore with the specified number of permits.
func New(permits int) Semaphore {
if permits <= 0 {
panic("permits must be greater than 0")
}
return make(chan struct{}, permits)
}
// Acquire acquires a permit. This call will block until a permit is available
// or the provided context is completed.
//
// If the provided context is completed, the method will return the
// cancellation error.
func (s Semaphore) Acquire(ctx context.Context) error {
select {
case <-ctx.Done():
return ctx.Err()
case s <- struct{}{}:
return nil
}
}
// TryAcquire acquires the semaphore without blocking.
// Returns true if the semaphore is acquired.
// Otherwise, returns false and leaves the semaphore unchanged.
func (s Semaphore) TryAcquire() bool {
select {
case s <- struct{}{}:
return true
default:
return false
}
}
// Release releases a permit.
func (s Semaphore) Release() {
select {
case <-s:
default:
panic("semaphore buffer is empty")
}
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/zhaochuninhefei/fabric-gm.git
git@gitee.com:zhaochuninhefei/fabric-gm.git
zhaochuninhefei
fabric-gm
fabric-gm
v0.0.2

搜索帮助