mirror of
https://github.com/kunkundi/crossdesk.git
synced 2025-10-27 04:35:34 +08:00
[fix] fix crash due to thread releasing
This commit is contained in:
@@ -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_);
|
||||
|
||||
@@ -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_;
|
||||
|
||||
Reference in New Issue
Block a user