[fix] fix crash due to thread releasing

This commit is contained in:
dijunkun
2025-03-24 17:39:29 +08:00
parent d17b29dfa4
commit 160ee9feef
15 changed files with 126 additions and 41 deletions

View File

@@ -3,7 +3,10 @@
#include "log.h"
ThreadBase::ThreadBase()
: running_(false), pause_(false), period_(std::chrono::milliseconds(100)) {}
: running_(false),
pause_(false),
period_(std::chrono::milliseconds(100)),
thread_name_("UnnamedThread") {}
ThreadBase::~ThreadBase() { Stop(); }
@@ -11,7 +14,7 @@ void ThreadBase::Start() {
{
std::lock_guard<std::mutex> lock(cv_mtx_);
if (running_) {
return; // Already running
return;
}
running_ = true;
}
@@ -24,10 +27,11 @@ void ThreadBase::Stop() {
{
std::lock_guard<std::mutex> lock(cv_mtx_);
if (!running_) {
return; // Already stopped
return;
}
running_ = false;
}
cv_.notify_all();
if (thread_.joinable()) {
thread_.join();
@@ -43,6 +47,16 @@ void ThreadBase::SetPeriod(std::chrono::milliseconds period) {
period_ = period;
}
void ThreadBase::SetThreadName(const std::string& name) {
std::lock_guard<std::mutex> lock(cv_mtx_);
thread_name_ = name;
}
std::string ThreadBase::GetThreadName() {
std::lock_guard<std::mutex> lock(cv_mtx_);
return thread_name_;
}
void ThreadBase::Run() {
while (running_) {
std::unique_lock<std::mutex> lock(cv_mtx_);

View File

@@ -5,6 +5,7 @@
#include <chrono>
#include <condition_variable>
#include <mutex>
#include <string>
#include <thread>
class ThreadBase {
@@ -20,6 +21,8 @@ class ThreadBase {
void Resume();
void SetPeriod(std::chrono::milliseconds period);
void SetThreadName(const std::string& name);
std::string GetThreadName();
virtual bool Process() = 0;
@@ -29,6 +32,7 @@ class ThreadBase {
private:
std::thread thread_;
std::chrono::milliseconds period_;
std::string thread_name_;
std::condition_variable cv_;
std::mutex cv_mtx_;