summaryrefslogtreecommitdiffstats
path: root/staging_vespalib/src/vespa/vespalib/util/clock.cpp
blob: 543a475480b3e078a12555fec24ca9b512fcadb4 (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
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include "clock.h"
#include <cassert>
#include <chrono>

namespace vespalib {


Clock::Clock(double timePeriod) :
     _timeNS(0u),
     _timePeriodMS(static_cast<uint32_t>(timePeriod*1000)),
     _lock(),
     _cond(),
     _stop(false),
     _running(false)
{
    setTime();
}

Clock::~Clock()
{
    assert(!_running);
}

void Clock::setTime() const
{
    _timeNS = fastos::ClockSteady::now();
}

void Clock::Run(FastOS_ThreadInterface *thread, void *arguments)
{
    (void) arguments;
    _running = true;
    std::unique_lock<std::mutex> guard(_lock);
    while ( ! thread->GetBreakFlag() && !_stop) {
        setTime();
        _cond.wait_for(guard, std::chrono::milliseconds(_timePeriodMS));
    }
    _running = false;
}

void
Clock::stop()
{
    std::lock_guard<std::mutex> guard(_lock);
    _stop = true;
    _cond.notify_all();
}

}