blob: c0a32197c07170a3aebb84eabf49db7382860af4 (
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
71
72
73
74
75
76
|
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "document_runnable.h"
#include <vespa/vespalib/util/exceptions.h>
namespace document {
Runnable::Runnable()
: _stateLock(),
_state(NOT_RUNNING)
{
}
Runnable::~Runnable() {
vespalib::MonitorGuard monitorGuard(_stateLock);
assert(_state == NOT_RUNNING);
}
bool Runnable::start(FastOS_ThreadPool& pool)
{
vespalib::MonitorGuard monitor(_stateLock);
while (_state == STOPPING) monitor.wait();
if (_state != NOT_RUNNING) return false;
_state = STARTING;
if (pool.NewThread(this) == nullptr) {
throw vespalib::IllegalStateException("Faled starting a new thread", VESPA_STRLOC);
}
return true;
}
bool Runnable::stop()
{
vespalib::MonitorGuard monitor(_stateLock);
if (_state == STOPPING || _state == NOT_RUNNING) return false;
GetThread()->SetBreakFlag();
_state = STOPPING;
return onStop();
}
bool Runnable::onStop()
{
return true;
}
bool Runnable::join() const
{
vespalib::MonitorGuard monitor(_stateLock);
assert ((_state != STARTING) && (_state != RUNNING));
while (_state != NOT_RUNNING) monitor.wait();
return true;
}
void Runnable::Run(FastOS_ThreadInterface*, void*)
{
{
vespalib::MonitorGuard monitor(_stateLock);
// Dont set state if its alreadyt at stopping. (And let run() be
// called even though about to stop for consistency)
if (_state == STARTING) {
_state = RUNNING;
}
}
// By not catching exceptions, they should abort whole application.
// We should thus not need to have a catch all to set state to not
// running.
run();
{
vespalib::MonitorGuard monitor(_stateLock);
_state = NOT_RUNNING;
monitor.broadcast();
}
}
}
|