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

a2mppw5e  于 2024-01-04  发布在  Go
关注(0)|答案(1)|浏览(103)

在Go语言的crypto/rand包中的Prime函数(生成可能的素数)中,它从crypto/internal/randutil包中调用MaybeReadByte函数(如下所示)。根据函数描述,我可以理解为什么使用它,但我不明白这个实现为什么有50%的机会阅读字节。难道不应该保证其中一个case在另一个之前运行吗?

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[:])
    }
}

字符串

irtuqstp

irtuqstp1#

不是应该保证一个案子比另一个先办吗?

根据质量标准:
如果一个或多个通信可以进行,则经由统一伪随机选择来选择可以进行的单个通信。
由于两个case读取相同的通道,它们总是能够同时进行。

相关问题