1 /**************************************************************************
3 * Copyright 2011 Jose Fonseca
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24 **************************************************************************/
27 * Simple OS abstraction.
29 * Mimics C++11 / boost threads.
32 #ifndef _OS_THREAD_HPP_
33 #define _OS_THREAD_HPP_
49 typedef CRITICAL_SECTION native_handle_type;
51 typedef pthread_mutex_t native_handle_type;
54 recursive_mutex(void) {
56 InitializeCriticalSection(&_native_handle);
58 pthread_mutexattr_t attr;
59 pthread_mutexattr_init(&attr);
60 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
61 pthread_mutex_init(&_native_handle, &attr);
62 pthread_mutexattr_destroy(&attr);
68 DeleteCriticalSection(&_native_handle);
70 pthread_mutex_destroy(&_native_handle);
77 EnterCriticalSection(&_native_handle);
79 pthread_mutex_lock(&_native_handle);
86 LeaveCriticalSection(&_native_handle);
88 pthread_mutex_unlock(&_native_handle);
93 native_handle_type _native_handle;
98 class thread_specific_ptr
106 static void destructor(void *ptr) {
107 delete static_cast<T *>(ptr);
112 thread_specific_ptr(void) {
114 dwTlsIndex = TlsAlloc();
116 pthread_key_create(&key, &destructor);
120 ~thread_specific_ptr() {
124 pthread_key_delete(key);
131 ptr = TlsGetValue(dwTlsIndex);
133 ptr = pthread_getspecific(key);
135 return static_cast<T*>(ptr);
138 T* operator -> (void) const
143 T& operator * (void) const
148 void reset(T* new_value=0) {
149 T * old_value = get();
151 TlsSetValue(dwTlsIndex, new_value);
153 pthread_setspecific(key, new_value);
163 #endif /* _OS_THREAD_HPP_ */