summaryrefslogtreecommitdiffstats
path: root/library/cpp/yt/system/thread_id.cpp
blob: 978c735df25481e8b21a6bb6c18d130fb82a1ec1 (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
#include "thread_id.h"

#include <util/system/thread.h>

#ifdef _unix_
#include <library/cpp/yt/misc/static_initializer.h>

#include <pthread.h>
#endif

namespace NYT {

////////////////////////////////////////////////////////////////////////////////

YT_DEFINE_THREAD_LOCAL(TSystemThreadId, CachedSystemThreadId, InvalidSystemThreadId);

YT_DEFINE_THREAD_LOCAL(TSequentialThreadId, CachedSequentialThreadId, InvalidSequentialThreadId);
std::atomic<TSequentialThreadId> SequentialThreadIdGenerator = InvalidSequentialThreadId;

namespace NDetail {

TSystemThreadId GetSystemThreadIdImpl()
{
    static_assert(std::is_same_v<TSystemThreadId, ::TThread::TId>);
    return ::TThread::CurrentThreadNumericId();
}

} // namespace NDetail

#ifdef _unix_
// The kernel tid is stable for the lifetime of a thread, so we cache it to
// avoid the |gettid| syscall on each call. After a |fork|, however, the
// surviving (calling) thread of the child gets a fresh kernel tid, so the
// cache must be invalidated there.
YT_STATIC_INITIALIZER(
    ::pthread_atfork(
        /*prepare*/ nullptr,
        /*parent*/  nullptr,
        /*child*/   [] { CachedSystemThreadId() = InvalidSystemThreadId; }));
#endif

////////////////////////////////////////////////////////////////////////////////

} // namespace NYT