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