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 case
s 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[:]) } }
No.
Since both case
s 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!