summaryrefslogtreecommitdiff
path: root/src/mbgl/util/thread_local.hpp
blob: 15d4d5652434c9ce75a8a71c27e1c57c46cd244c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#pragma once

#include <mbgl/util/logging.hpp>
#include <mbgl/util/noncopyable.hpp>

#include <cassert>
#include <stdexcept>

#include <pthread.h>

namespace mbgl {
namespace util {

template <class T>
class ThreadLocal : public noncopyable {
public:
    ThreadLocal() {
        int ret = pthread_key_create(&key, [](void *ptr) {
            delete reinterpret_cast<T *>(ptr);
        });

        if (ret) {
            throw std::runtime_error("Failed to init local storage key.");
        }
    }

    ~ThreadLocal() {
        if (pthread_key_delete(key)) {
            Log::Error(Event::General, "Failed to delete local storage key.");
            assert(false);
        }
    }

    T* get() {
        auto* ret = reinterpret_cast<T*>(pthread_getspecific(key));
        if (!ret) {
            return nullptr;
        }

        return ret;
    }

    void set(T* ptr) {
        if (pthread_setspecific(key, ptr)) {
            throw std::runtime_error("Failed to set local storage.");
        }
    }

private:
    pthread_key_t key;
};

} // namespace util
} // namespace mbgl