gnustep/libs-base

Inconsistent behavior of rand() between Linux/Windows on new threads after srand() on previous/main thread

jcaselman-keysight opened this issue · 2 comments

I'm curious where you all come down on this, as it seems to be sort of a grey area in that the GNUstep application behaves differently on different platforms, but the different behavior is a result of differences in the implementation of the c runtime.

On Windows, each newly created thread starts with the same random seed (1), which is not inherited from the 'parent' thread, resulting in a call to rand() on each new thread producing the same result unless srand() is called inside that thread first.

You can see in this commit and associated CI run that a testcase demonstrating this setup fails on Windows but passes on Linux

Do you consider this a GNUstep problem or no? I poked around a bit at what a fix might look like, but so far wasn't able to find a tweak to NSThread.m that resulted in the outcome I was after

rfm commented

I would say that, if portability is an objective for you, you have an application bug in that the application is calling the rand() function (not a part of the API). It's clearly not a GNUstep problem, because rand() is nothing to do with GNUstep.

Now, as far as I can recall there's no equivalent of rand() in the OpenStep/Cocoa APIs, but GNUstep does have an extension API which is similar; the +[NSData dataWithRandomBytesOfLength:] method. Using that should be good for portable code (at last between linux and windows, other systems may require code contribution).
The random data provided by that method should be suitable as a seed for a pseudo-random number generator, or usable as random data directly (as long as speed is not critical).

Thanks @rfm, I thought that might be the case but figured it was worth checking