Skip to content

Random::DEFAULT is thread unsafe #16157

@ysbaddaden

Description

@ysbaddaden

The Random::DEFAULT constant isn't a alias for the Random::PCG32 implementation (sadly) but a global instance of it. It's initialized once then shared across all the threads, but the algorithm is thread unsafe (two or more threads generating a random number will mess with the internal state).

A solution could be to deprecate the constant, to introduce a thread local instance of the default RNG, and to expose it as Random.default.

EDIT: even with a thread local, the Enumerable#sample method is still unsafe for types whose #each may yield the current fiber because it takes then reuses a reference to the default instance (thread local) while the fiber can be resumed by any thread (oops).

EDIT: same for Crystal::System::File.mktemp since it tries to open on each iteration, which may yield the fiber.

Metadata

Metadata

Assignees

Labels

kind:bugA bug in the code. Does not apply to documentation, specs, etc.topic:multithreading

Type

Projects

Status

In Progress

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions