代码拉取完成,页面将自动刷新
/*
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")
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。