1 //=== llvm/Support/Unix/ThreadLocal.inc - Unix Thread Local Data -*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
9 // This file implements the Unix specific (non-pthread) ThreadLocal class.
11 //===----------------------------------------------------------------------===//
13 //===----------------------------------------------------------------------===//
14 //=== WARNING: Implementation here must contain only generic UNIX code that
15 //=== is guaranteed to work on *all* UNIX variants.
16 //===----------------------------------------------------------------------===//
18 #include "llvm/Config/config.h"
20 #if defined(HAVE_PTHREAD_H) && defined(HAVE_PTHREAD_GETSPECIFIC)
29 ThreadLocalImpl::ThreadLocalImpl() : data() {
30 static_assert(sizeof(pthread_key_t) <= sizeof(data), "size too big");
31 pthread_key_t* key = reinterpret_cast<pthread_key_t*>(&data);
32 int errorcode = pthread_key_create(key, nullptr);
33 assert(errorcode == 0);
37 ThreadLocalImpl::~ThreadLocalImpl() {
38 pthread_key_t* key = reinterpret_cast<pthread_key_t*>(&data);
39 int errorcode = pthread_key_delete(*key);
40 assert(errorcode == 0);
44 void ThreadLocalImpl::setInstance(const void* d) {
45 pthread_key_t* key = reinterpret_cast<pthread_key_t*>(&data);
46 int errorcode = pthread_setspecific(*key, d);
47 assert(errorcode == 0);
51 void *ThreadLocalImpl::getInstance() {
52 pthread_key_t* key = reinterpret_cast<pthread_key_t*>(&data);
53 return pthread_getspecific(*key);
56 void ThreadLocalImpl::removeInstance() {
64 ThreadLocalImpl::ThreadLocalImpl() : data() { }
65 ThreadLocalImpl::~ThreadLocalImpl() { }
66 void ThreadLocalImpl::setInstance(const void* d) { data = const_cast<void*>(d);}
67 void *ThreadLocalImpl::getInstance() { return data; }
68 void ThreadLocalImpl::removeInstance() { setInstance(0); }