1.Use std::move to initialize std::thread; 2.Fix thread cannot exit error

This commit is contained in:
dijunkun
2024-06-13 15:46:05 +08:00
parent eee3b2a95e
commit c575a9170c
14 changed files with 48 additions and 39 deletions

View File

@@ -4,21 +4,22 @@
ThreadBase::ThreadBase() {}
ThreadBase::~ThreadBase() { Stop(); }
ThreadBase::~ThreadBase() {
if (!stop_) {
Stop();
}
}
void ThreadBase::Start() {
if (!thread_) {
thread_ = std::make_unique<std::thread>(&ThreadBase::Run, this);
}
std::thread t(&ThreadBase::Run, this);
thread_ = std::move(t);
stop_ = false;
}
void ThreadBase::Stop() {
stop_ = true;
if (thread_ && thread_->joinable()) {
thread_->join();
if (thread_.joinable()) {
stop_ = true;
thread_.join();
}
}

View File

@@ -7,7 +7,7 @@
class ThreadBase {
public:
ThreadBase();
~ThreadBase();
virtual ~ThreadBase();
public:
void Start();
@@ -22,7 +22,7 @@ class ThreadBase {
void Run();
private:
std::unique_ptr<std::thread> thread_ = nullptr;
std::thread thread_;
std::atomic<bool> stop_{false};
std::atomic<bool> pause_{false};