GPrivate doesn't need to have a scary limit in its contract
Currently, GPrivate
documentation says:
* #GPrivate is a very limited resource (as far as 128 per program,
* shared between all libraries). It is also not possible to destroy a
* #GPrivate after it has been used. As such, it is only ever acceptable
* to use #GPrivate in static scope, and even then sparingly so.
This is correct, because it allocates from pthread_key_create()
or from TlsAlloc()
, which are both limited per process.
In presence of unknown needs of other libraries, this makes it a somewhat scary tool to use. At the same time, the API is very useful, matching commonly used thread_local
in C++. GLib itself seems to have around 15 uses, and in fact it would be nice to use more. For example, make g_random_xxx()
thread-local to avoid locking in #2474.
The suggested solution is to do the same thing as C++ runtime does: only allocate a single slot from underlying OS and use this slot to keep a pointer to GLib's own in-memory array of slots.
This way, the limit can be removed completely. The small downside is that values will now have additional cost of one pointer dereferencing, but this isn't much and C++ already sees this compromise to be worthy.