3 回答

TA貢獻(xiàn)1828條經(jīng)驗(yàn) 獲得超4個(gè)贊
使用緩沖區(qū)大小為 1 的通道作為互斥鎖。
l := make(chan struct{}, 1)
鎖:
l <- struct{}{}
開鎖:
<-l
嘗試鎖定:
select {
case l <- struct{}{}:
// lock acquired
<-l
default:
// lock not acquired
}
嘗試超時(shí):
select {
case l <- struct{}{}:
// lock acquired
<-l
case <-time.After(time.Minute):
// lock not acquired
}

TA貢獻(xiàn)1859條經(jīng)驗(yàn) 獲得超6個(gè)贊
我想你在這里問了幾件不同的事情:
標(biāo)準(zhǔn)庫(kù)中是否存在此功能?不,它沒有。您可能可以在其他地方找到實(shí)現(xiàn) - 這可以使用標(biāo)準(zhǔn)庫(kù)(例如原子)來實(shí)現(xiàn)。
為什么標(biāo)準(zhǔn)庫(kù)中不存在此功能:您在問題中提到的問題是一個(gè)討論。在 go-nuts 郵件列表上也有幾個(gè)討論,有幾個(gè) Go 代碼開發(fā)人員貢獻(xiàn):鏈接 1,鏈接 2。通過谷歌搜索很容易找到其他討論。
我怎樣才能設(shè)計(jì)我的程序,這樣我就不需要這個(gè)了?
(3) 的答案更加微妙,取決于您的具體問題。你的問題已經(jīng)說了
可以將它實(shí)現(xiàn)為一個(gè)工作隊(duì)列(帶有通道和東西),但在那種情況下,衡量和利用所有可用的 CPU 變得更加困難
沒有詳細(xì)說明為什么與檢查互斥鎖狀態(tài)相比,使用所有 CPU 會(huì)更加困難。
在 Go 中,只要鎖定方案變得重要,您通常就需要通道。它不應(yīng)該更慢,而且應(yīng)該更易于維護(hù)。

TA貢獻(xiàn)1812條經(jīng)驗(yàn) 獲得超5個(gè)贊
go-lock
除了 Lock 和 Unlock 之外,還實(shí)現(xiàn)TryLock
,TryLockWithTimeout
和功能。TryLockWithContext
它提供了控制資源的靈活性。
例子:
package main
import (
? ? "fmt"
? ? "time"
? ? "context"
? ? lock "github.com/viney-shih/go-lock"
)
func main() {
? ? casMut := lock.NewCASMutex()
? ? casMut.Lock()
? ? defer casMut.Unlock()
? ? // TryLock without blocking
? ? fmt.Println("Return", casMut.TryLock()) // Return false
? ? // TryLockWithTimeout without blocking
? ? fmt.Println("Return", casMut.TryLockWithTimeout(50*time.Millisecond)) // Return false
? ? // TryLockWithContext without blocking
? ? ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
? ? defer cancel()
? ? fmt.Println("Return", casMut.TryLockWithContext(ctx)) // Return false
? ? // Output:
? ? // Return false
? ? // Return false
? ? // Return false
}

TA貢獻(xiàn)1780條經(jīng)驗(yàn) 獲得超4個(gè)贊
PMutex 實(shí)現(xiàn) RTryLock(ctx context.Context) 和 TryLock(ctx context.Context)
// ctx - some context
ctx := context.Background()
mx := mfs.PMutex{}
isLocked := mx.TryLock(ctx)
if isLocked {
? ? // DO Something
? ? mx.Unlock()
} else {
? ? // DO Something else
}
- 3 回答
- 0 關(guān)注
- 222 瀏覽
添加回答
舉報(bào)