代码拉取完成,页面将自动刷新
同步操作将从 LEE377/线程池 强制同步,此操作会覆盖自 Fork 仓库以来所做的任何修改,且无法恢复!!!
确定后同步将在后台操作,完成时将刷新页面,请耐心等待。
#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;
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。