nothings / stb

stb single-file public domain libraries for C/C++
https://twitter.com/nothings
Other
25.9k stars 7.66k forks source link

[stb_image] allow for thread-safe error reporting #652

Open DavidLudwig opened 5 years ago

DavidLudwig commented 5 years ago

stb_image, according to its docs, does not have thread-safe error reporting. This was discussed in https://github.com/nothings/stb/issues/309, perhaps among other places.

A way to load images via stb_image, in a thread-safe manner, would make stb_image more usable in 3rd-party libraries, whereby the user is a developer, and may be attempting to load images from multiple threads.

Here are a few, initial thoughts, on how this might be implemented, hopefully without breaking things:

  1. alternate function names (whither stbi_load2, stbi_load_ex, stbi2_load, or stbi3_load ?), with either a different return value, or with output parameters
  2. callback-based error reporting: if and when an error is found, an optional, user-provided callback function is invoked (which could be thread-safe). Altering the callback would, perhaps, not be thread-safe, and if so, should be noted as such.
DavidLudwig commented 5 years ago

Here is another possibility for implementation:

  1. use C11 and C++11's thread_local keyword, if available
nothings commented 5 years ago

The problem is finding a thread-safe solution that works on all supported compilers. There's an infamous problem with keyword-based thread-local storage on for versions of Windows before Vista. I'm not sure it's safe to drop support for those.

DavidLudwig commented 5 years ago

This might be a bit too hackish, but what about one or more optional, preprocessor macros, which could allow a 'thread_local' to be injected into stb_image, by the library-or-app that integrates it? If it wasn't defined, then the older, TLS-free implementation is used.

nothings commented 5 years ago

That might be reasonable, since the thing we need to avoid is putting in a partial implementation that only works on some platforms, because then the documentation is like "this is thread-safe on platforms X,Y,Z and compilers S,T,V" and nobody wants that. So if we put it onto the developer, then they at least know which platforms they've made it work for.