BRL.Random: Thread Safety

BlitzMax Forums/BlitzMax Module Tweaks/BRL.Random: Thread Safety

grable(Posted 2016) [#1]
Thread Safe BRL.Random. Updated: March 13 2016 - v1.09

Each thread has its own seed using a thread-data slot instead of a global.
A thread starts with the main thread seed of so its important to call SeedRnd inside the thread to get different random values.
An additional function RndSeedMain for getting the main thread seed manually.



Test:
Function test:Object( data:Object)
	Print data.ToString()
	Print "~tmain="+RndSeedMain()
	Print "~tseed="+RndSeed()
	SeedRnd data.ToString().ToInt()
	Print "~tnewseed="+RndSeed()
EndFunction

SeedRnd 10
CreateThread test, "20"
Delay 250
CreateThread test, "30"
Delay 250
CreateThread test, "40"
Delay 250
CreateThread test, "50"
Delay 250

Print "10"
Print "~tmain="+RndSeedMain()
Print "~tseed="+RndSeed()




Derron(Posted 2016) [#2]
Shouldn't SeedRnd adjust some kind of "global" - which is the initial seed of each thread started _afterwards_

Reading a simple numeric value should be threadsafe, isn't it?
Running SeedRnd within a thread should then write to a thread-scoped variable.


bye
Ron


grable(Posted 2016) [#3]
It changes the seed for each new random number as well, so it was never really thread safe ;)
It still produced random numbers, but they were not deterministic in threaded mode as they would all clobber the same global.

I cant see a way to change the ThreadData slot of a new thread without modifying the threading api (and then adding a dependency on BRL.Random in the process).
Which is why i added RndSeedMain() so one can do that manually.


grable(Posted 2016) [#4]
I took your suggestion Derron, and made it start with main thread seed.
I had to steal seed 0 for myself though, using it as an init signal when i get the thread data.

Version 1.09 - Made seed==0 get seed from main thread (so threads new always start with main thread seed)