aboutsummaryrefslogtreecommitdiffstats
path: root/searchlib/src/vespa/searchlib/util/runnable.h
blob: 4b3532097622530b82a82249f09435da245247ea (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
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#pragma once

#include <mutex>
#include <condition_variable>
#include <vespa/fastos/thread.h>

namespace search {

class Runnable : public FastOS_Runnable
{
protected:
    std::mutex              _lock;
    std::condition_variable _cond;
    bool                    _done;
    bool                    _stopped;

public:
    Runnable() :
        _lock(), _cond(), _done(false), _stopped(false)
    { }
    void Run(FastOS_ThreadInterface *, void *) override {
        doRun();

        std::lock_guard<std::mutex> guard(_lock);
        _stopped = true;
        _cond.notify_all();
    }
    virtual void doRun() = 0;
    void stop() {
        std::lock_guard<std::mutex> guard(_lock);
        _done = true;
    }
    void join() {
        std::unique_lock<std::mutex> guard(_lock);
        while (!_stopped) {
            _cond.wait(guard);
        }
    }
};

} // search