通过在引用线程对象传递取消引用的this
指针来在函数对象构造函数中创建线程是好是坏?
- 下面的代码有问题吗?
- 可以对其进行任何改进以达到低于目标吗?
目标是在类对象超出范围时优雅地结束线程。
#include <iostream>
#include <chrono>
#include <future>
#include <thread>
class MyThread {
private:
std::atomic<bool> exit;
std::thread t;
public:
MyThread() : exit(false) {
t = std::thread(std::ref(*this));
}
~MyThread() {
exit.store(true, std::memory_order_relaxed);
if (t.joinable()) {
t.join();
}
}
void operator()() {
while (!exit.load(std::memory_order_relaxed)) {
std::cout << "."; // some more meaningful work here
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
};
int main() {
MyThread t;
std::cin.get();
return 0;
}
它可能偶尔有效,但它不安全。它可能会生成争用条件,因为您在尚未完成构造的对象上启动线程,从而导致未定义的行为。