2 * Copyright 2017 Facebook, Inc.
\r
4 * Licensed under the Apache License, Version 2.0 (the "License");
\r
5 * you may not use this file except in compliance with the License.
\r
6 * You may obtain a copy of the License at
\r
8 * http://www.apache.org/licenses/LICENSE-2.0
\r
10 * Unless required by applicable law or agreed to in writing, software
\r
11 * distributed under the License is distributed on an "AS IS" BASIS,
\r
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
\r
13 * See the License for the specific language governing permissions and
\r
14 * limitations under the License.
\r
17 #include <folly/portability/PThread.h>
\r
19 #if !FOLLY_HAVE_PTHREAD && _WIN32
\r
20 #include <unordered_map>
\r
24 namespace portability {
\r
26 static thread_local struct PThreadLocalMap {
\r
27 PThreadLocalMap() = default;
\r
28 ~PThreadLocalMap() {
\r
29 for (auto kv : keyMap) {
\r
30 // Call destruction callbacks if they exist.
\r
31 if (kv.second.second != nullptr) {
\r
32 kv.second.second(kv.second.first);
\r
37 int createKey(pthread_key_t* key, void (*destructor)(void*)) {
\r
38 auto ret = TlsAlloc();
\r
39 if (ret == TLS_OUT_OF_INDEXES) {
\r
43 keyMap.emplace(*key, std::make_pair(nullptr, destructor));
\r
47 int deleteKey(pthread_key_t key) {
\r
48 if (!TlsFree(key)) {
\r
55 void* getKey(pthread_key_t key) {
\r
56 return TlsGetValue(key);
\r
59 int setKey(pthread_key_t key, void* value) {
\r
60 if (!TlsSetValue(key, value)) {
\r
63 keyMap[key].first = value;
\r
67 std::unordered_map<pthread_key_t, std::pair<void*, void (*)(void*)>> keyMap{};
\r
70 int pthread_key_create(pthread_key_t* key, void (*destructor)(void*)) {
\r
71 return s_tls_key_map.createKey(key, destructor);
\r
74 int pthread_key_delete(pthread_key_t key) {
\r
75 return s_tls_key_map.deleteKey(key);
\r
78 void* pthread_getspecific(pthread_key_t key) {
\r
79 return s_tls_key_map.getKey(key);
\r
82 int pthread_setspecific(pthread_key_t key, const void* value) {
\r
83 // Yes, the PThread API really is this bad -_-...
\r
84 return s_tls_key_map.setKey(key, const_cast<void*>(value));
\r