thread_local_inl.h 1.39 KB
Newer Older
gejun's avatar
gejun committed
1
// Copyright (c) 2014 Baidu, Inc.
gejun's avatar
gejun committed
2 3 4 5 6 7 8 9 10 11 12 13
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// 
//     http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
gejun's avatar
gejun committed
14 15 16 17

// Author: Ge,Jun (gejun@baidu.com)
// Date: Tue Sep 16 12:39:12 CST 2014

gejun's avatar
gejun committed
18 19
#ifndef BUTIL_THREAD_LOCAL_INL_H
#define BUTIL_THREAD_LOCAL_INL_H
gejun's avatar
gejun committed
20

21
namespace butil {
gejun's avatar
gejun committed
22 23 24 25 26 27 28 29 30 31 32 33

namespace detail {

template <typename T>
class ThreadLocalHelper {
public:
    inline static T* get() {
        if (__builtin_expect(value != NULL, 1)) {
            return value;
        }
        value = new (std::nothrow) T;
        if (value != NULL) {
34
            butil::thread_atexit(delete_object<T>, value);
gejun's avatar
gejun committed
35 36 37 38 39 40 41 42 43 44 45 46 47 48
        }
        return value;
    }
    static BAIDU_THREAD_LOCAL T* value;
};

template <typename T> BAIDU_THREAD_LOCAL T* ThreadLocalHelper<T>::value = NULL;

}  // namespace detail

template <typename T> inline T* get_thread_local() {
    return detail::ThreadLocalHelper<T>::get();
}

49
}  // namespace butil
gejun's avatar
gejun committed
50

gejun's avatar
gejun committed
51
#endif  // BUTIL_THREAD_LOCAL_INL_H