diff --git a/stdlib/Random/src/RNGs.jl b/stdlib/Random/src/RNGs.jl index 899147313fb2bc..a10f820edef651 100644 --- a/stdlib/Random/src/RNGs.jl +++ b/stdlib/Random/src/RNGs.jl @@ -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 @@ -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 diff --git a/stdlib/Random/src/Random.jl b/stdlib/Random/src/Random.jl index fc9469cb1652e7..5daa9a6733655c 100644 --- a/stdlib/Random/src/Random.jl +++ b/stdlib/Random/src/Random.jl @@ -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!,