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 31, 2019
1 parent ffdee15 commit 8cfb814
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 1 deletion.
10 changes: 10 additions & 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 Expand Up @@ -306,6 +307,15 @@ const THREAD_RNGs = MersenneTwister[]
end
function __init__()
resize!(empty!(THREAD_RNGs), Threads.nthreads()) # ensures that we didn't save a bad object

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
end


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

## general definitions

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 @@ -778,3 +778,7 @@ end
@testset "RNGs broadcast as scalars: T" for T in (MersenneTwister, RandomDevice)
@test length.(rand.(T(), 1:3)) == 1:3
end

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

0 comments on commit 8cfb814

Please sign in to comment.