停止当前正在运行的线程C
Stopping a currently running thread c++
我有一个经理类,该类为成员的执行方法创建了线程。
int Task::Execute()
{
try
{
setTaskSeqByName();
for (int i = 0; i < mTaskSequence.size(); i++)
{
if(mCurrentStatus == "running")
mTaskSequence[i]->Execute();
}
}
catch (std::exception ex)
{
return -1;
}
return 0;
}
我希望能够运行一个不同的线程,因此我能够执行一个将更改mCurrentStatus
变量的停止,以便循环停止以及mTaskSequence[i]
任务。
最好的方法是什么?
谢谢!
您不能暂停或停止理论上的运行线程。对另一个跑步线进行精细的谷物控制是一个挑战。但是,使用条件变化,您可以模拟一个如下所示:
#include "conio.h"
#include <iostream>
#include <thread>
#include <atomic>
#include <chrono>
#include <mutex>
#include <condition_variable>
using namespace std;
class foo_t
{
private:
atomic<bool>& running_;
thread worker_;
mutex lock_;
condition_variable signal_;
atomic<bool> pause_;
public:
foo_t(atomic<bool>& running): running_(running)
{
pause_ = false;
worker_ = thread([&]() { run(); });
}
~foo_t()
{
worker_.join();
}
};
方法和属性:
void foo_t::run()
{
while (running_)
{
unique_lock<mutex> lock(lock_);
signal_.wait(lock, [&]() { return !running_ || !pause_; });
if (!running_) return;
cout << ". ";
this_thread::sleep_for(chrono::milliseconds(100));
}
}
condition_variable& foo_t::GetSignal()
{
return signal_;
}
void foo_t::SetPause(bool flag)
{
pause_ = flag;
}
主要程序
int main()
{
atomic<bool> running = true;
foo_t foo(running);
char ch;
cout << "Press r to Run Press p to Pause or Press to Exit n ";
while ( (ch = getch()) != 'p' || ch !='r' || ch != 'x')
{
if (ch == 'p' )
{
cout << "pausedn ";
foo.SetPause(true);
foo.GetSignal().notify_one();
}
else
if (ch == 'r' )
{
cout << "runningn ";
foo.SetPause(false);
foo.GetSignal().notify_one();
}
else
if (ch == 'x')
{
running = false;
foo.GetSignal().notify_one();
break;
}
}
running = false;
return 0;
}
相关文章:
- 使用基类中的派生方法运行线程,而无需使用模板
- 使用 ubuntu 终端在 c++ 上运行线程类的问题
- 将项目添加到队列时运行线程
- 运行线程和线程对象之间的关系
- 在 gtest 中运行线程
- 是否有一种可接受的运行线程或按顺序执行的方法
- 从类中运行线程
- 如何在第三方函数调用之前同时运行线程
- 在优先级最低的核心中运行线程
- 在C++中并行运行线程
- 在C 11中的背景中运行线程
- 在运行线程中处理事件
- 使用对象生存期运行线程
- WINAPI CreateThread并不总是运行线程
- 树莓派与 c++ 运行线程,在网络上发布数据
- 使用变量类型 std::function 运行线程
- Eclipse CDT 多线程调试不是最佳的 - 如何以独占方式运行线程
- 在 C 语言的后台运行线程
- 正在运行线程
- 在远程计算机上运行线程