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