Skip to content

Commit

Permalink
Random: add a global RANDOM_DEVICE generator
Browse files Browse the repository at this point in the history
Creating a RandomDevice object is cheap but it opens a file
on unix systems, so one can't call `rand(RandomDevice())`
repeatedly too quicly (e.g. in a loop). It can therefore be
convenient to have a readily available generator.
  • Loading branch information
rfourquet committed Oct 4, 2018
1 parent 60cff80 commit 4167cdc
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 1 deletion.
1 change: 1 addition & 0 deletions stdlib/Random/src/RNGs.jl
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ RandomDevice
RandomDevice(::Nothing) = RandomDevice()
seed!(rng::RandomDevice) = rng

const RANDOM_DEVICE = RandomDevice()

## MersenneTwister

Expand Down
10 changes: 9 additions & 1 deletion stdlib/Random/src/Random.jl
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export rand!, randn!,
shuffle, shuffle!,
randperm, randperm!,
randcycle, randcycle!,
AbstractRNG, MersenneTwister, RandomDevice
AbstractRNG, MersenneTwister, RandomDevice, RANDOM_DEVICE

## general definitions

Expand Down Expand Up @@ -264,6 +264,14 @@ rand( ::Type{X}, d::Integer, dims::Integer...) where {X} = rand(X
function __init__()
try
seed!()
if !Sys.iswindows()
# open /dev/urandom "in-place" (in RANDOM_DEVICE.file)
RANDOM_DEVICE.file.handle = pointer(RANDOM_DEVICE.file.ios)
systemerror("opening file /dev/urandom",
ccall(:ios_file, Ptr{Cvoid},
(Ptr{UInt8}, Cstring, Cint, Cint, Cint, Cint),
RANDOM_DEVICE.file.ios, "/dev/urandom", 1, 0, 0, 0) == C_NULL)
end
catch ex
Base.showerror_nostdio(ex,
"WARNING: Error during initialization of module Random")
Expand Down
4 changes: 4 additions & 0 deletions stdlib/Random/test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -694,3 +694,7 @@ end
a = rand(Int, 1)
@test shuffle(a) == a
end

@testset "RANDOM_DEVICE" begin
@test rand(Random.RANDOM_DEVICE) isa Float64
end

0 comments on commit 4167cdc

Please sign in to comment.