停止当前正在运行的线程C

Stopping a currently running thread c++

本文关键字:运行 线程      更新时间:2023-10-16

我有一个经理类,该类为成员的执行方法创建了线程。

 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;
}