Golang并發(fā)工具包之信號(hào)量(Semaphore)

Go雖然天生的支持高并發(fā),但是有些場(chǎng)景下我們還是需要控制協(xié)程同時(shí)并發(fā)處理的數(shù)量,在Java的juc包中已經(jīng)提供了類(lèi)似功能的工具類(lèi)-信號(hào)量(Semaphore),它是基于AQS實(shí)現(xiàn)的。Go的SDK中并沒(méi)有提供類(lèi)似的API,我們通過(guò)goroutine和channel實(shí)現(xiàn)一個(gè)簡(jiǎn)單的Semaphore,并提供:獲取許可(Acquire())、指定時(shí)間內(nèi)獲取許可(TryAcquireOnTime)、釋放許可(Release())等方法,具體實(shí)現(xiàn)如下:

type Semaphore struct {
    permits int      // 許可數(shù)量
    channel chan int // 通道
}

/* 創(chuàng)建信號(hào)量 */
func NewSemaphore(permits int) *Semaphore {
    return &Semaphore{channel: make(chan int, permits), permits: permits}
}

/* 獲取許可 */
func (s *Semaphore) Acquire() {
    s.channel <- 0
}

/* 釋放許可 */
func (s *Semaphore) Release() {
    <-s.channel
}

/* 嘗試獲取許可 */
func (s *Semaphore) TryAcquire() bool {
    select {
    case s.channel <- 0:
        return true
    default:
        return false
    }
}

/* 嘗試指定時(shí)間內(nèi)獲取許可 */
func (s *Semaphore) TryAcquireOnTime(timeout time.Duration) bool {
    for {
        select {
        case s.channel <- 0:
            return true
        case <-time.After(timeout):
            return false
        }
    }
}

/* 當(dāng)前可用的許可數(shù) */
func (s *Semaphore) AvailablePermits() int {
    return s.permits - len(s.channel)
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容