ThreadLocal.inc 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. //=== llvm/Support/Unix/ThreadLocal.inc - Unix Thread Local Data -*- C++ -*-===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements the Unix specific (non-pthread) ThreadLocal class.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. //===----------------------------------------------------------------------===//
  13. //=== WARNING: Implementation here must contain only generic UNIX code that
  14. //=== is guaranteed to work on *all* UNIX variants.
  15. //===----------------------------------------------------------------------===//
  16. #include "llvm/Config/config.h"
  17. #if defined(HAVE_PTHREAD_H) && defined(HAVE_PTHREAD_GETSPECIFIC)
  18. #include <cassert>
  19. #include <pthread.h>
  20. #include <stdlib.h>
  21. namespace llvm {
  22. using namespace sys;
  23. ThreadLocalImpl::ThreadLocalImpl() : data() {
  24. static_assert(sizeof(pthread_key_t) <= sizeof(data), "size too big");
  25. pthread_key_t* key = reinterpret_cast<pthread_key_t*>(&data);
  26. int errorcode = pthread_key_create(key, nullptr);
  27. assert(errorcode == 0);
  28. (void) errorcode;
  29. }
  30. ThreadLocalImpl::~ThreadLocalImpl() {
  31. pthread_key_t* key = reinterpret_cast<pthread_key_t*>(&data);
  32. int errorcode = pthread_key_delete(*key);
  33. assert(errorcode == 0);
  34. (void) errorcode;
  35. }
  36. void ThreadLocalImpl::setInstance(const void* d) {
  37. pthread_key_t* key = reinterpret_cast<pthread_key_t*>(&data);
  38. int errorcode = pthread_setspecific(*key, d);
  39. assert(errorcode == 0);
  40. (void) errorcode;
  41. }
  42. void *ThreadLocalImpl::getInstance() {
  43. pthread_key_t* key = reinterpret_cast<pthread_key_t*>(&data);
  44. return pthread_getspecific(*key);
  45. }
  46. void ThreadLocalImpl::removeInstance() {
  47. setInstance(nullptr);
  48. }
  49. }
  50. #else
  51. namespace llvm {
  52. using namespace sys;
  53. ThreadLocalImpl::ThreadLocalImpl() : data() { }
  54. ThreadLocalImpl::~ThreadLocalImpl() { }
  55. void ThreadLocalImpl::setInstance(const void* d) { data = const_cast<void*>(d);}
  56. void *ThreadLocalImpl::getInstance() { return data; }
  57. void ThreadLocalImpl::removeInstance() { setInstance(0); }
  58. }
  59. #endif