Skip to content

Commit 2f1cb8f

Browse files
committed
Random: add a global RANDOM_DEVICE generator
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.
1 parent 429e2d5 commit 2f1cb8f

File tree

3 files changed

+14
-1
lines changed

3 files changed

+14
-1
lines changed

stdlib/Random/src/RNGs.jl

+1
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,7 @@ RandomDevice
6767
RandomDevice(::Nothing) = RandomDevice()
6868
srand(rng::RandomDevice) = rng
6969

70+
const RANDOM_DEVICE = RandomDevice()
7071

7172
## MersenneTwister
7273

stdlib/Random/src/Random.jl

+9-1
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ export srand,
2626
shuffle, shuffle!,
2727
randperm, randperm!,
2828
randcycle, randcycle!,
29-
AbstractRNG, MersenneTwister, RandomDevice,
29+
AbstractRNG, MersenneTwister, RandomDevice, RANDOM_DEVICE
3030
randjump
3131

3232

@@ -244,6 +244,14 @@ rand( ::Type{X}, d::Integer, dims::Integer...) where {X} = rand(X
244244
function __init__()
245245
try
246246
srand()
247+
if !Sys.iswindows()
248+
# open /dev/urandom "in-place" (in RANDOM_DEVICE.file)
249+
RANDOM_DEVICE.file.handle = pointer(RANDOM_DEVICE.file.ios)
250+
systemerror("opening file /dev/urandom",
251+
ccall(:ios_file, Ptr{Cvoid},
252+
(Ptr{UInt8}, Cstring, Cint, Cint, Cint, Cint),
253+
RANDOM_DEVICE.file.ios, "/dev/urandom", 1, 0, 0, 0) == C_NULL)
254+
end
247255
catch ex
248256
Base.showerror_nostdio(ex,
249257
"WARNING: Error during initialization of module Random")

stdlib/Random/test/runtests.jl

+4
Original file line numberDiff line numberDiff line change
@@ -677,3 +677,7 @@ end
677677
@test eltype(Random.UInt52(UInt128)) == UInt128
678678
@test eltype(Random.UInt104()) == UInt128
679679
end
680+
681+
@testset "RANDOM_DEVICE" begin
682+
@test rand(Random.RANDOM_DEVICE) isa Float64
683+
end

0 commit comments

Comments
 (0)