1 Star 0 Fork 1

行走的皮卡丘/线程池

forked from LEE377/线程池 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
BaseThread.cpp 2.00 KB
一键复制 编辑 原始数据 按行查看 历史
LEE377 提交于 2023-07-13 06:29 . 线程池文件
#include "BaseThread.h"
BaseThread::BaseThread() {
m_thread = unique_ptr<thread>(new thread(&BaseThread::Run, this));
execFunc = nullptr;
m_thread->detach();
}
void BaseThread::ThreadStart(){
unique_lock<mutex> lock(mtx);
m_state = RunningState::START;
cond.notify_one();
}
void BaseThread::ThreadPause() {
unique_lock<mutex> lock(mtx);
m_state = RunningState::PAUSE;
}
void BaseThread::ThreadStop() {
unique_lock<mutex> lock(mtx);
m_state = RunningState::STOP;
cond.notify_one();
cond_taskEmpty.notify_one();
}
BaseThread::RunningState BaseThread::GetRunningState() {
return m_state;
}
void BaseThread::Run() {
m_state = RunningState::START;
cout << "thread ID:" << this_thread::get_id << " is start!\n";
// 之所以这种方法终止线程安全,是因为该执行的模块都一起执行完了才退出循环。
while (GetRunningState() != RunningState::STOP) {
WaitIfPaused();
if (GetRunningState() == RunningState::START) TaskAction();
}
cout << "Thread ID : " << this_thread::get_id << " is stop.\n";
}
void BaseThread::TaskAction() {
unique_lock<mutex> lock(mtx);
// 限制在此地WAIT而别的地方没有该置位,是因为希望在START过程中发出需要任务的请求而非在PAUSE过程中也可以添加任务
m_state = RunningState::WAIT;
cond_taskEmpty.wait(lock, [this] {return execFunc!=nullptr || m_state == RunningState::STOP; });
if (m_state == RunningState::STOP) return;
m_state = RunningState::START;
if(execFunc()) cout << "thread: " << this_thread::get_id() << " task exec successful!\n";
else cout << "thread: " << this_thread::get_id() << " task exec failed!\n";
execFunc = nullptr;
cond_taskFull.notify_one();
}
void BaseThread::WaitIfPaused() {
unique_lock<mutex> lock(mtx);
cond.wait(lock, [this] {return GetRunningState() != RunningState::PAUSE; }); //不为暂停
}
bool BaseThread::AddTask(function<bool()> func) {
unique_lock<mutex> lock(mtx);
cond_taskFull.wait(lock, [this] {return execFunc == nullptr; });
execFunc = func;
cond_taskEmpty.notify_one();
return true;
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/wsy-lyy/thread-pool.git
git@gitee.com:wsy-lyy/thread-pool.git
wsy-lyy
thread-pool
线程池
master

搜索帮助