From 17e92e4b1902206ecb8459a86a4f7cfbf246d887 Mon Sep 17 00:00:00 2001 From: cxl Date: Wed, 7 Aug 2013 11:40:10 +0000 Subject: [PATCH] Core: Random now fork safe git-svn-id: svn://ultimatepp.org/upp/trunk@6236 f0d560ea-af0d-0410-9eb7-867de7ffcac7 --- uppsrc/Core/Random.cpp | 21 +++++++++++++-------- uppsrc/Core/Util.h | 1 - uppsrc/Core/src.tpp/MathUtil$en-us.tpp | 9 +-------- 3 files changed, 14 insertions(+), 17 deletions(-) diff --git a/uppsrc/Core/Random.cpp b/uppsrc/Core/Random.cpp index ec1061449..01bd3a2f0 100644 --- a/uppsrc/Core/Random.cpp +++ b/uppsrc/Core/Random.cpp @@ -58,6 +58,9 @@ struct MTrand { dword mt[N]; int mti; /* mti==N+1 means mt[N] is not initialized */ dword mag01[2]; +#ifdef PLATFORM_POSIX + int pid; +#endif void seed(); void init_genrand(dword s); @@ -160,6 +163,9 @@ MTrand::MTrand() mag01[0] = 0; mag01[1] = MATRIX_A; seed(); +#ifdef PLATFORM_POSIX + pid = getpid(); +#endif } void MTrand::seed() @@ -192,14 +198,6 @@ thread__ MTrand *sRng; thread__ byte sRb[sizeof(MTrand)]; #endif -void SeedRandom() -{ - if(!sRng) { - sRng = new(sRb) MTrand; - } - sRng->seed(); -} - void SeedRandom(dword *seed, int len){ if(!sRng) { sRng = new(sRb) MTrand; @@ -219,6 +217,13 @@ dword Random() if(!sRng) { sRng = new(sRb) MTrand; } +#ifdef PLATFORM_POSIX // Be fork safe... + int pid = getpid(); + if(sRng->pid != pid) { + sRng->seed(); + sRng->pid = pid; + } +#endif return sRng->genrand(); } diff --git a/uppsrc/Core/Util.h b/uppsrc/Core/Util.h index f9db5bfeb..0d7b621b5 100644 --- a/uppsrc/Core/Util.h +++ b/uppsrc/Core/Util.h @@ -296,7 +296,6 @@ qword Random64(); qword Random64(qword n); double Randomf(); -void SeedRandom(); void SeedRandom(dword *seed,int len); void SeedRandom(dword seed = 0); diff --git a/uppsrc/Core/src.tpp/MathUtil$en-us.tpp b/uppsrc/Core/src.tpp/MathUtil$en-us.tpp index 9ee6d15d3..adb744eeb 100644 --- a/uppsrc/Core/src.tpp/MathUtil$en-us.tpp +++ b/uppsrc/Core/src.tpp/MathUtil$en-us.tpp @@ -95,14 +95,7 @@ d],[@(0.0.255) int]_[*@3 len])&] [s5;:SeedRandom`(dword`): [@(0.0.255) void]_[* SeedRandom]([_^dword^ dword]_[*@3 seed]_`=_[@3 0 ])&] [s2;%% Seeds random with single value [%-*@3 seed]. This is good to -get always the same sequence of numbers (for the same seed)&] -[s3; &] -[s4; &] -[s5;:SeedRandom`(`): [@(0.0.255) void]_[* SeedRandom]()&] -[s2; Seeds random from the host platform randomness sources. Note -that this is done by default by random number generator, there -is no need to call this function unless you are doing something -special.&] +get always the same sequence of numbers (for the same seed).&] [s3;%% &] [s4; &] [s5;:ZeroArray`(x`): [* ZeroArray]([*@3 x])&]