ThreadLocal.h 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. //===- llvm/Support/ThreadLocal.h - 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 declares the llvm::sys::ThreadLocal class.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #ifndef LLVM_SUPPORT_THREADLOCAL_H
  13. #define LLVM_SUPPORT_THREADLOCAL_H
  14. #include "llvm/Support/DataTypes.h"
  15. #include "llvm/Support/Threading.h"
  16. #include <cassert>
  17. namespace llvm {
  18. namespace sys {
  19. // ThreadLocalImpl - Common base class of all ThreadLocal instantiations.
  20. // YOU SHOULD NEVER USE THIS DIRECTLY.
  21. class ThreadLocalImpl {
  22. typedef uint64_t ThreadLocalDataTy;
  23. /// Platform-specific thread local data.
  24. ///
  25. /// This is embedded in the class and we avoid malloc'ing/free'ing it,
  26. /// to make this class more safe for use along with CrashRecoveryContext.
  27. union {
  28. char data[sizeof(ThreadLocalDataTy)];
  29. ThreadLocalDataTy align_data;
  30. };
  31. public:
  32. ThreadLocalImpl();
  33. virtual ~ThreadLocalImpl();
  34. void setInstance(const void* d);
  35. void *getInstance();
  36. void removeInstance();
  37. };
  38. /// ThreadLocal - A class used to abstract thread-local storage. It holds,
  39. /// for each thread, a pointer a single object of type T.
  40. template<class T>
  41. class ThreadLocal : public ThreadLocalImpl {
  42. public:
  43. ThreadLocal() : ThreadLocalImpl() { }
  44. /// get - Fetches a pointer to the object associated with the current
  45. /// thread. If no object has yet been associated, it returns NULL;
  46. T* get() { return static_cast<T*>(getInstance()); }
  47. // set - Associates a pointer to an object with the current thread.
  48. void set(T* d) { setInstance(d); }
  49. // erase - Removes the pointer associated with the current thread.
  50. void erase() { removeInstance(); }
  51. };
  52. }
  53. }
  54. #endif