0%

使用RAII思想来管理线程

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class thread_guard {
public:
explicit thread_guard(thread &t) : _t(t) {}
~thread_guard() {
if (_t.joinable()) {
_t.join();
}
}
thread_guard(const thread_guard &) = delete;
thread_guard &operator=(const thread_guard &) = delete;

private:
thread &_t;
};

int main() {
for (int i = 0; i < 10; ++i) {
thread t{[](int x) { cout << x << endl; }, i};
thread_guard tg{t};
}
return 0;
}