Skip to content

Commit

Permalink
Random: RandomDevice() share /dev/[u]random file handles (#27936)
Browse files Browse the repository at this point in the history
  • Loading branch information
rfourquet authored and KristofferC committed Apr 11, 2020
1 parent bc6b77d commit 2e53315
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 16 deletions.
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

0 comments on commit 2e53315

Please sign in to comment.