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

王林
Release: 2024-02-06 09:55:03
forward
443 people have browsed it

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

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template