aboutsummaryrefslogtreecommitdiffstats
path: root/util/generic/singleton.cpp
blob: b193a589abc0194f6f19dbff52231eb67f1eec81 (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
#include "singleton.h" 
 
#include <util/system/spinlock.h> 
#include <util/system/thread.h> 
#include <util/system/sanitizers.h>
 
#include <cstring> 
 
namespace { 
    static inline bool MyAtomicTryLock(TAtomic& a, TAtomicBase v) noexcept {
        return AtomicCas(&a, v, 0); 
    } 
 
    static inline bool MyAtomicTryAndTryLock(TAtomic& a, TAtomicBase v) noexcept {
        return (AtomicGet(a) == 0) && MyAtomicTryLock(a, v); 
    } 
 
    static inline TAtomicBase MyThreadId() noexcept {
        const TAtomicBase ret = TThread::CurrentThreadId(); 
 
        if (ret) { 
            return ret; 
        } 
 
        //clash almost impossible, ONLY if we have threads with ids 0 and 1! 
        return 1; 
    } 
} 
 
void NPrivate::FillWithTrash(void* ptr, size_t len) { 
#if defined(NDEBUG) 
    Y_UNUSED(ptr);
    Y_UNUSED(len);
#else 
    if constexpr (NSan::TSanIsOn()) {
        Y_UNUSED(ptr);
        Y_UNUSED(len);
    } else {
        memset(ptr, 0xBA, len);
    }
#endif 
} 
 
void NPrivate::LockRecursive(TAtomic& lock) noexcept {
    const TAtomicBase id = MyThreadId(); 
 
    Y_VERIFY(AtomicGet(lock) != id, "recursive singleton initialization");
 
    if (!MyAtomicTryLock(lock, id)) { 
        TSpinWait sw; 
 
        do { 
            sw.Sleep(); 
        } while (!MyAtomicTryAndTryLock(lock, id)); 
    } 
} 
 
void NPrivate::UnlockRecursive(TAtomic& lock) noexcept {
    Y_VERIFY(AtomicGet(lock) == MyThreadId(), "unlock from another thread?!?!");
    AtomicUnlock(&lock); 
}