summaryrefslogtreecommitdiffstats
path: root/library/cpp/threading/thread_local/generic.cpp
blob: eca63d76bc659a031ea8ae049182bf88f2a843aa (plain) (blame)
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#include "generic.h"

#include "thread_local.h"

namespace {
    class TThreadLocalStorage
        : public NThreading::IGenericLocalStorage
    {
    public:
        TData* GetData() const override {
            return Data_.Get();
        }
    private:
        NThreading::TThreadLocalValue<TData, NThreading::EThreadLocalImpl::StdThreadLocal> Data_;
    };

    class TThreadLocalContext
        : public NThreading::IGLSContext
    {
        bool IsCurrent() const override {
            return true;
        }

        THolder<NThreading::IGenericLocalStorage> MakeStorage() const override {
            return MakeHolder<TThreadLocalStorage>();
        }
    };

    class TContextRegistry {
    public:
        TContextRegistry() {
            Register(MakeHolder<TThreadLocalContext>());
        }

        size_t Count() const {
            return Count_.load();
        }

        const NThreading::IGLSContext& Get(size_t index) const {
            return *Contexts_[index];
        }

        void Register(THolder<NThreading::IGLSContext> context) {
            with_lock (Lock_) {
                const size_t index = Count_.load();
                Y_ENSURE(index < NThreading::NDetail::MaxGLSContexts, "Too many generic local contexts registered");
                Contexts_[index] = std::move(context);
                Count_.store(index + 1);
            }
        }
    private:
        TAdaptiveLock Lock_;
        std::atomic<size_t> Count_ = 0;
        std::array<THolder<NThreading::IGLSContext>, NThreading::NDetail::MaxGLSContexts> Contexts_ = {};
    };

    TContextRegistry& Registry() {
        static TContextRegistry registry;
        return registry;
    }
}

namespace NThreading {
    void RegisterGLSContext(THolder<IGLSContext> context) {
        Registry().Register(std::move(context));
    }

    namespace NDetail {
        size_t GLSContextCount() {
            return Registry().Count();
        }

        const IGLSContext& GetGLSContext(size_t index) {
            return Registry().Get(index);
        }
    }
}