SDL_systls.c 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /*
  2. Simple DirectMedia Layer
  3. Copyright (C) 1997-2023 Sam Lantinga <slouken@libsdl.org>
  4. This software is provided 'as-is', without any express or implied
  5. warranty. In no event will the authors be held liable for any damages
  6. arising from the use of this software.
  7. Permission is granted to anyone to use this software for any purpose,
  8. including commercial applications, and to alter it and redistribute it
  9. freely, subject to the following restrictions:
  10. 1. The origin of this software must not be misrepresented; you must not
  11. claim that you wrote the original software. If you use this software
  12. in a product, an acknowledgment in the product documentation would be
  13. appreciated but is not required.
  14. 2. Altered source versions must be plainly marked as such, and must not be
  15. misrepresented as being the original software.
  16. 3. This notice may not be removed or altered from any source distribution.
  17. */
  18. #include "../../SDL_internal.h"
  19. #if SDL_THREAD_WINDOWS
  20. #include "../../core/windows/SDL_windows.h"
  21. #include "SDL_thread.h"
  22. #include "../SDL_thread_c.h"
  23. #if WINAPI_FAMILY_WINRT
  24. #include <fibersapi.h>
  25. #ifndef TLS_OUT_OF_INDEXES
  26. #define TLS_OUT_OF_INDEXES FLS_OUT_OF_INDEXES
  27. #endif
  28. #define TlsAlloc() FlsAlloc(NULL)
  29. #define TlsSetValue FlsSetValue
  30. #define TlsGetValue FlsGetValue
  31. #endif
  32. static DWORD thread_local_storage = TLS_OUT_OF_INDEXES;
  33. static SDL_bool generic_local_storage = SDL_FALSE;
  34. SDL_TLSData *SDL_SYS_GetTLSData(void)
  35. {
  36. if (thread_local_storage == TLS_OUT_OF_INDEXES && !generic_local_storage) {
  37. static SDL_SpinLock lock;
  38. SDL_AtomicLock(&lock);
  39. if (thread_local_storage == TLS_OUT_OF_INDEXES && !generic_local_storage) {
  40. DWORD storage = TlsAlloc();
  41. if (storage != TLS_OUT_OF_INDEXES) {
  42. SDL_MemoryBarrierRelease();
  43. thread_local_storage = storage;
  44. } else {
  45. generic_local_storage = SDL_TRUE;
  46. }
  47. }
  48. SDL_AtomicUnlock(&lock);
  49. }
  50. if (generic_local_storage) {
  51. return SDL_Generic_GetTLSData();
  52. }
  53. SDL_MemoryBarrierAcquire();
  54. return (SDL_TLSData *)TlsGetValue(thread_local_storage);
  55. }
  56. int SDL_SYS_SetTLSData(SDL_TLSData *data)
  57. {
  58. if (generic_local_storage) {
  59. return SDL_Generic_SetTLSData(data);
  60. }
  61. if (!TlsSetValue(thread_local_storage, data)) {
  62. return SDL_SetError("TlsSetValue() failed");
  63. }
  64. return 0;
  65. }
  66. #endif /* SDL_THREAD_WINDOWS */
  67. /* vi: set ts=4 sw=4 expandtab: */