Home  >  Article  >  Backend Development  >  How does MaybeReadByte's use of channels provide "random" behavior in Go?

How does MaybeReadByte's use of channels provide "random" behavior in Go?

王林
王林forward
2024-02-06 09:55:03391browse

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

Question content

In the Prime function (generating possible prime numbers) in Go's crypto/rand package, it calls The MaybeReadByte function in the crypto/internal/randutil package (shown below). Based on the function description, I can understand why it is used, but I don't understand how this implementation has a 50% chance of reading bytes. Shouldn't one of the cases be guaranteed to run before the other?

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

Correct answer


No.

According to specification:

Since both cases read the same channel, they can always do so simultaneously.

The above is the detailed content of How does MaybeReadByte's use of channels provide "random" behavior in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete