首頁 >後端開發 >Golang >Go中如何取得有期限的鎖?

Go中如何取得有期限的鎖?

Patricia Arquette
Patricia Arquette原創
2024-10-29 15:22:02685瀏覽

How to Acquire a Lock with a Deadline in Go?

Go 中透過 Deadline 取得鎖

Go 中,sync.Mutex 類型只提供 Lock() 和 Unlock() 方法。對於應在截止日期內嘗試取得鎖或可能立即中止的情況,沒有內建解決方案。

建議的解決方案:通道作為互斥體

另一種方法是使用緩衝區大小為 1 的通道來模擬互斥體。透過發送和接收單一空結構體值 (struct{}{}),可以執行鎖定和解鎖操作。

Lock:

<code class="go">l := make(chan struct{}, 1)
l <- struct{}{}</code>

解鎖:

<code class="go"><-l</code>

試試🎜>

嘗試超時鎖定:
<code class="go">select {
case l <- struct{}{}:
    // lock acquired
    <-l
default:
    // lock not acquired
}</code>

在提供的範例中,假設s.someObj 是從鍵到值的對應。

<code class="go">select {
case l <- struct{}{}:
    // lock acquired
    <-l
case <-time.After(time.Minute):
    // lock not acquired
}</code>

範例1:延遲敏感程式碼的LockBefore()

範例2:用於更新統計資料的TryLock()
<code class="go">// DoTheThing locks before performing expensive computations.
func (s *RPCService) DoTheThing(ctx context.Context, ...) ... {
    l := make(chan struct{}, 1)
    select {
    case l <- struct{}{}:
        defer <-l
        ... expensive computation based on internal state ...
    default:
        return s.cheapCachedResponse[req.Parameter]
    }
}</code>

範例2:用於更新統計資料的TryLock()範例2:用於更新統計資料的TryLock()

<code class="go">// updateObjStats attempts to lock and update stats.
func (s *StatsObject) updateObjStats(key, value interface{}) {
    l := make(chan struct{}, 1)
    select {
    case l <- struct{}{}:
        defer <-l
        ... update stats ...
        ... fill in s.cheapCachedResponse ...
    default:
        // skip locked object
    }
}

// UpdateStats attempts to lock and update stats for all objects.
func (s *StatsObject) UpdateStats() {
    s.someObj.Range(s.updateObjStats)
}</code>
例如🎜>

以上是Go中如何取得有期限的鎖?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn