Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Random: make RandomDevice() instances share the same /dev/urandom file #27936

Merged
merged 5 commits into from
Dec 3, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 12 additions & 12 deletions stdlib/Random/src/RNGs.jl
Original file line number Diff line number Diff line change
Expand Up @@ -19,24 +19,24 @@ if Sys.iswindows()
end
else # !windows
struct RandomDevice <: AbstractRNG
file::IOStream
unlimited::Bool

RandomDevice(; unlimited::Bool=true) =
new(open(unlimited ? "/dev/urandom" : "/dev/random"), unlimited)
RandomDevice(; unlimited::Bool=true) = new(unlimited)
end

rand(rd::RandomDevice, sp::SamplerBoolBitInteger) = read( rd.file, sp[])
rand(rd::RandomDevice, sp::SamplerBoolBitInteger) = read(getfile(rd), sp[])

function serialize(s::AbstractSerializer, rd::RandomDevice)
Serialization.serialize_type(s, typeof(rd))
serialize(s, rd.unlimited)
end
function deserialize(s::AbstractSerializer, t::Type{RandomDevice})
unlimited = deserialize(s)
return RandomDevice(unlimited=unlimited)
function getfile(rd::RandomDevice)
devrandom = rd.unlimited ? DEV_URANDOM : DEV_RANDOM
# TODO: there is a data-race, this can leak up to nthreads() copies of the file descriptors,
# so use a "thread-once" utility once available
isassigned(devrandom) || (devrandom[] = open(rd.unlimited ? "/dev/urandom" : "/dev/random"))
devrandom[]
end

const DEV_RANDOM = Ref{IOStream}()
const DEV_URANDOM = Ref{IOStream}()

end # os-test

# NOTE: this can't be put within the if-else block above
Expand All @@ -48,7 +48,7 @@ for T in (Bool, BitInteger_types...)
A
end
else
@eval rand!(rd::RandomDevice, A::Array{$T}, ::SamplerType{$T}) = read!(rd.file, A)
@eval rand!(rd::RandomDevice, A::Array{$T}, ::SamplerType{$T}) = read!(getfile(rd), A)
end
end

Expand Down
6 changes: 2 additions & 4 deletions stdlib/Random/src/Random.jl
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,8 @@ using Base.GMP: Limb

using Base: BitInteger, BitInteger_types, BitUnsigned, require_one_based_indexing

import Base: copymutable, copy, copy!, ==, hash, convert
using Serialization
import Serialization: serialize, deserialize
import Base: rand, randn
import Base: copymutable, copy, copy!, ==, hash, convert,
rand, randn

export rand!, randn!,
randexp, randexp!,
Expand Down