BackgroundWorker and random generator issue

Hi

I use BackgroundWorker to perform in background a CPU demanding task (generation of random levels) but I found a really annoying bug. Indeed, each time I run my level generator function with BackgroundWorker.doWork, I obtain exactly the same generated level. My function is using Std.random() to generate random numbers and it appear that, when called from a function called itself with BackgroundWorker.doWork, numbers generated by Std.random() are not random at all. Each time, this is exactly the SAME succession of numbers that are returned by the consecutive calls of Std.random().
But if I call my level generator function directly from the main process now (so without using a BackgroundWorker), the numbers returned by Std.random() are trully random (I obtain a different level each time I run my function, as expected)

How can I fix this? is there some seed generator that need to be passed to BackgroundWorker to allow it to generate random numbers or is this a bug?

Hmm, that sounds like a Haxe bug :frowning:

Perhaps you can do the Math.random () first, and pass it in when you call doWork?

On the C++ target, Haxe calls this hxcpp function, which in turn calls rand().

As the rand() documentation says, srand() is the solution, so try this:

untyped __cpp__('srand(time(NULL))');

Math.random() suffer exactly the same issue. And I can’t pass it when I call doWork as my level generator function needs multiple random number (an undefined number as this number of random numbers needed is also random and depend on previous ones)

@player_03 : error C3861: 'time' : identificateur introuvable . Looks like it can’t access the c++ time() function. Don’t know why

I guess time.h isn’t included by default. Try adding this in front of your class definition:

@:cppInclude('time.h')
1 Like

Perfect. That worked. Thanks a lot!

Now I have true random numbers generated in BackgroundWorker :wink:

Technically they’re still pseudo-random, but at least now they don’t repeat.