ironarachne / world

This is a fantasy world generation CLI and set of Go packages for the same.
MIT License
48 stars 9 forks source link

Requesting value with id is not always the same #33

Closed KnutZuidema closed 4 years ago

KnutZuidema commented 4 years ago

Since the global random generator of the rand package is used for all random values, there can be cases where, when multiple values with an id are requested simultaneously, the value returned is not the same.

Reproduction:
Open multiple pages with an ID at the same time, e.g. in Firefox by bookmarking them in a folder and clicking "Open All in Tabs".

Reason:
The reason for this a simple race condition. When a page with an ID is requested the global random generator is seeded with that ID. Then the request is executed just like a normal one. However, if another request with an ID arrives while generation is not yet completed, it might happen that the new seed is injected in between calls for random values, thus resulting in different random values.

Solution:
I would suggest to inject a random generator seeded with the ID into a context and use that generator instead of global functions for generating random values.
This would require restructuring the random package insofar that the functions are also available as methods of a generator type.
It would also require adding context parameters to all functions/methods requiring random values.

I would be happy to do the work required if this is something that you would like to see fixed.

BenOvermyer commented 4 years ago

This would resolve a long standing bug that has, quite frankly, driven me nuts. If you'd like to work on it you're more than welcome to.