File indexing completed on 2024-04-28 05:46:51

0001 /*****************************************************************************
0002  *   Copyright 2015 - 2015 Yichao Yu <yyc1992@gmail.com>                     *
0003  *                                                                           *
0004  *   This program is free software; you can redistribute it and/or modify    *
0005  *   it under the terms of the GNU Lesser General Public License as          *
0006  *   published by the Free Software Foundation; either version 2.1 of the    *
0007  *   License, or (at your option) version 3, or any later version accepted   *
0008  *   by the membership of KDE e.V. (or its successor approved by the         *
0009  *   membership of KDE e.V.), which shall act as a proxy defined in          *
0010  *   Section 6 of version 3 of the license.                                  *
0011  *                                                                           *
0012  *   This program is distributed in the hope that it will be useful,         *
0013  *   but WITHOUT ANY WARRANTY; without even the implied warranty of          *
0014  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU       *
0015  *   Lesser General Public License for more details.                         *
0016  *                                                                           *
0017  *   You should have received a copy of the GNU Lesser General Public        *
0018  *   License along with this library. If not,                                *
0019  *   see <http://www.gnu.org/licenses/>.                                     *
0020  *****************************************************************************/
0021 
0022 #ifndef _QTC_UTILS_THREAD_H_
0023 #define _QTC_UTILS_THREAD_H_
0024 
0025 #include <pthread.h>
0026 
0027 // Replaces thread_local since clang on OSX doesn't really support it.
0028 template<typename T>
0029 class ThreadLocal {
0030     pthread_key_t m_key;
0031 public:
0032     ThreadLocal()
0033     {
0034         pthread_key_create(&m_key, [] (void *ptr) {
0035                 delete reinterpret_cast<T*>(ptr);
0036             });
0037     }
0038     ~ThreadLocal()
0039     {
0040         pthread_key_delete(m_key);
0041     }
0042     T*
0043     get() const
0044     {
0045         T *v = reinterpret_cast<T*>(pthread_getspecific(m_key));
0046         if (!v) {
0047             v = new T();
0048             pthread_setspecific(m_key, reinterpret_cast<void*>(v));
0049         }
0050         return v;
0051     }
0052     T*
0053     operator->() const
0054     {
0055         return get();
0056     }
0057 };
0058 
0059 #endif