ThreadLocal.inc 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. //=== llvm/Support/Unix/ThreadLocal.inc - Unix Thread Local Data -*- C++ -*-===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements the Unix specific (non-pthread) ThreadLocal class.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //===----------------------------------------------------------------------===//
  14. //=== WARNING: Implementation here must contain only generic UNIX code that
  15. //=== is guaranteed to work on *all* UNIX variants.
  16. //===----------------------------------------------------------------------===//
  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