Join GitHub today
GitHub is home to over 50 million developers working together to host and review code, manage projects, and build software together.Sign up
GitHub is where the world builds software
Millions of developers and companies build, ship, and maintain their software on GitHub — the largest and most advanced development platform in the world.
proposal: math/rand: export functions for creating locked sources #25057
The default Source provided by
In practice, most libraries seem to choose option 1, because it's by far the most convenient - it's much easier to call
Unfortunately, because option 1 is so convenient, and because so many libraries default to the default, applications which use multiple libraries that import
It's easy to spot this sort of contention with pprof if you know to look for it (which is not always a given). However, it's actually not particularly straightforward to fix. If a library relies on the default source, it cannot also easily provide a way for callers to specify a different source, since the top-level functions don't expose the default source in any way (
For callers who are running into contention problems, it's not easy to retrofit this functionality into existing libraries either. Even if I'm willing to fork one of my dependencies to rely on a non-default source, the lack of either a common interface type or common functions for generating thread-safe sources means it's not a straightforward find-and-replace.
As an example of what this retrofitting would look like, I've switched our top-level application here to use a non-default Source, but with a sync.Pool for thread-safety. The performance gains are significant, but it'd be more painful to apply this change to the other dependencies in the project which still use the default source:
If instead we had common functions in the standard library for initializing thread-safe RNGs, it would be easier to establish a community practice of expecting libraries to allow callers to specify the Source, while also guaranteeing that the Source is in fact still safe for concurrent usage.