Repository navigation
Expand file tree
/
Copy paththread.h
More file actions
97 lines (75 loc) · 2.3 KB
/
Copy paththread.h
File metadata and controls
97 lines (75 loc) · 2.3 KB
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef CC_ASYNC_THREAD_H_
#define CC_ASYNC_THREAD_H_
#include <functional>
#include <string>
#include <thread>
#include "absl/synchronization/mutex.h"
namespace minigo {
class Thread {
public:
virtual ~Thread();
Thread() = default;
explicit Thread(std::string name);
Thread(Thread&&) = default;
Thread& operator=(Thread&&) = default;
std::thread::native_handle_type handle() { return impl_.native_handle(); }
virtual void Start();
virtual void Join();
private:
virtual void Run() = 0;
std::string name_;
std::thread impl_;
};
class LambdaThread : public Thread {
public:
template <typename T>
explicit LambdaThread(T closure) : closure_(std::move(closure)) {}
template <typename T>
LambdaThread(std::string name, T closure)
: Thread(std::move(name)), closure_(std::move(closure)) {}
LambdaThread(LambdaThread&&) = default;
LambdaThread& operator=(LambdaThread&&) = default;
private:
void Run() override;
std::function<void()> closure_;
};
// A thread whose `Start` method blocks until the thread is running and has
// called `SignalStarted` at least once.
// This can be useful to serialize the order in which threads start.
class BlockingStartThread : public Thread {
public:
BlockingStartThread() = default;
explicit BlockingStartThread(std::string name) : Thread(std::move(name)) {}
void Start() override {
Thread::Start();
absl::MutexLock lock(&mutex_);
while (!started_) {
cond_var_.Wait(&mutex_);
}
}
protected:
void SignalStarted() {
absl::MutexLock lock(&mutex_);
started_ = true;
cond_var_.Signal();
}
private:
absl::Mutex mutex_;
absl::CondVar cond_var_;
bool started_ = false;
};
} // namespace minigo
#endif // CC_ASYNC_THREAD_H_