首頁  >  文章  >  後端開發  >  MaybeReadByte 對通道的使用如何在 Go 中提供「隨機」行為?

MaybeReadByte 對通道的使用如何在 Go 中提供「隨機」行為?

王林
王林轉載
2024-02-06 09:55:03395瀏覽

MaybeReadByte 对通道的使用如何在 Go 中提供“随机”行为?

問題內容

在Go 的crypto/rand 套件中的Prime 函數(產生可能的質數)中,它調用crypto/internal/randutil 套件中的MaybeReadByte 函數(如下所示)。根據函數描述,我可以理解為什麼使用它,但我不明白這個實現如何有 50% 的機會讀取位元組。難道不應該保證 cases 之一先於另一個運行嗎?

var (
    closedChanOnce sync.Once
    closedChan     chan struct{}
)

// MaybeReadByte reads a single byte from r with ~50% probability. This is used
// to ensure that callers do not depend on non-guaranteed behaviour, e.g.
// assuming that rsa.GenerateKey is deterministic w.r.t. a given random stream.
//
// This does not affect tests that pass a stream of fixed bytes as the random
// source (e.g. a zeroReader).
func MaybeReadByte(r io.Reader) {
    closedChanOnce.Do(func() {
        closedChan = make(chan struct{})
        close(closedChan)
    })

    select {
    case <-closedChan:
        return
    case <-closedChan:
        var buf [1]byte
        r.Read(buf[:])
    }
}

正確答案


#沒有。

根據規範

由於兩個 cases 讀取相同的通道,因此它們總是能夠同時進行。

以上是MaybeReadByte 對通道的使用如何在 Go 中提供「隨機」行為?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:stackoverflow.com。如有侵權,請聯絡admin@php.cn刪除