Convert newlines in folly/portability/PThread.cpp
[folly.git] / folly / portability / PThread.cpp
1 /*
2  * Copyright 2017 Facebook, Inc.
3  *
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
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 #include <folly/portability/PThread.h>
18
19 #if !FOLLY_HAVE_PTHREAD && _WIN32
20 #include <unordered_map>
21 #include <utility>
22
23 namespace folly {
24 namespace portability {
25 namespace pthread {
26 static thread_local struct PThreadLocalMap {
27   PThreadLocalMap() = default;
28   ~PThreadLocalMap() {
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);
33       }
34     }
35   }
36
37   int createKey(pthread_key_t* key, void (*destructor)(void*)) {
38     auto ret = TlsAlloc();
39     if (ret == TLS_OUT_OF_INDEXES) {
40       return -1;
41     }
42     *key = ret;
43     keyMap.emplace(*key, std::make_pair(nullptr, destructor));
44     return 0;
45   }
46
47   int deleteKey(pthread_key_t key) {
48     if (!TlsFree(key)) {
49       return -1;
50     }
51     keyMap.erase(key);
52     return 0;
53   }
54
55   void* getKey(pthread_key_t key) {
56     return TlsGetValue(key);
57   }
58
59   int setKey(pthread_key_t key, void* value) {
60     if (!TlsSetValue(key, value)) {
61       return -1;
62     }
63     keyMap[key].first = value;
64     return 0;
65   }
66
67   std::unordered_map<pthread_key_t, std::pair<void*, void (*)(void*)>> keyMap{};
68 } s_tls_key_map;
69
70 int pthread_key_create(pthread_key_t* key, void (*destructor)(void*)) {
71   return s_tls_key_map.createKey(key, destructor);
72 }
73
74 int pthread_key_delete(pthread_key_t key) {
75   return s_tls_key_map.deleteKey(key);
76 }
77
78 void* pthread_getspecific(pthread_key_t key) {
79   return s_tls_key_map.getKey(key);
80 }
81
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));
85 }
86 }
87 }
88 }
89 #endif