aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/actors/dnscachelib/timekeeper.h
blob: 0528d8549c3a04cd6794826563517d5031cc2c9d (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
#pragma once

#include <util/datetime/base.h>
#include <util/generic/singleton.h>
#include <util/string/cast.h>
#include <util/system/thread.h>
#include <util/system/event.h>
#include <util/system/env.h>

#include <cstdlib>

/* Keeps current time accurate up to 1/10 second */

class TTimeKeeper {
public:
    static TInstant GetNow(void) {
        return TInstant::MicroSeconds(GetTime());
    }

    static time_t GetTime(void) {
        return Singleton<TTimeKeeper>()->CurrentTime.tv_sec;
    }

    static const struct timeval& GetTimeval(void) {
        return Singleton<TTimeKeeper>()->CurrentTime;
    }

    TTimeKeeper()
        : Thread(&TTimeKeeper::Worker, this)
    {
        ConstTime = !!GetEnv("TEST_TIME");
        if (ConstTime) {
            try {
                CurrentTime.tv_sec = FromString<ui32>(GetEnv("TEST_TIME"));
            } catch (TFromStringException exc) {
                ConstTime = false;
            }
        }
        if (!ConstTime) {
            gettimeofday(&CurrentTime, nullptr);
            Thread.Start();
        }
    }

    ~TTimeKeeper() {
        if (!ConstTime) {
            Exit.Signal();
            Thread.Join();
        }
    }

private:
    static const ui32 UpdateInterval = 100000;
    struct timeval CurrentTime;
    bool ConstTime;
    TSystemEvent Exit;
    TThread Thread;

    static void* Worker(void* arg) {
        TTimeKeeper* owner = static_cast<TTimeKeeper*>(arg);

        do {
            /* Race condition may occur here but locking looks too expensive */

            gettimeofday(&owner->CurrentTime, nullptr);
        } while (!owner->Exit.WaitT(TDuration::MicroSeconds(UpdateInterval)));

        return nullptr;
    }
};