如何停止C ++中的线程执行 [英] How to stop the thread execution in C++

查看:465
本文介绍了如何停止C ++中的线程执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在主程序中创建了一个线程,一旦主程序终止,线程执行必须停止。我正在使用 reader.join(); 终止线程执行。



我尝试使用下面提到的代码,我使用的是 thread.join(); 函数,但无法终止线程。在主程序之后,我的线程也继续执行。

  #include< algorithm> 
#include< array>
#include< atomic>
#include< mutex>
#include< queue>
#include< cstdint>
#include< thread>
#include< vector>

使用命名空间std;
使用命名空间std :: chrono;

typedef对< int,Mat> pairImage;

类PairComp {
public:
bool operator()(const pairImage& n1,const pairImage& n2)const
{
if(n1。 first == n2.first)
返回n1.first> n2.first;
返回n1.first> n2.first;
}
};

int main(int argc,char * argv [])
{
Mutex mtxQueueInput;
queue< pairImage> queueInput;
int总计= 0;
atomic< bool> bReading(true);
线程读取器([&](){
int idxInputImage = 0;
而(true){
Mat img = imread( img_folder /);
mtxQueueInput.lock();
queueInput.push(make_pair(idxInputImage ++,img));
if(queueInput.size()> = 100){
mtxQueueInput.unlock();
cout<<警告输入队列的大小为<< queueInput.size();
//睡眠片刻
sleep(2);
}
else {
mtxQueueInput.unlock();
}
}
bReading.store(false);
});

而(true){
pair< int,Mat> pairIndexImage;
mtxQueueInput.lock();
if(queueInput.empty()){
mtxQueueInput.unlock();
如果(bReading.load())
继续;
否则
休息;
}
else {
//从输入队列获取图像
pairIndexImage = queueInput.front();
queueInput.pop();
}
mtxQueueInput.unlock();
cv :: Mat frame = pairIndexImage.second;

cv :: rectangle(frame,cv :: Rect {100,100,100,100},0xff);
}

cv :: imshow( out_image,frame);
waitKey(1);

如果(total ++ == 200)
休息;

if(reader.joinable()){
reader.join();
}

返回0;
}


解决方案

thread.join()不会导致线程终止,它会一直等到线程结束。结束执行是线程的责任,例如,通过定期检查某个条件(例如标志)来结束执行。



您已经有一个原子标志 bReading ,这似乎导致线程退出。

  if(queueInput.empty()){
mtxQueueInput.unlock();
如果(bReading.load())
继续;
否则
休息; //当队列为空并且bReading == false

时,线程将退出在调用 thread.join()之前, bReading = false 在外部线程中。

  bReading = false; 
reader.join();

请注意, bReading.store(false);




注意:您不需要调用 atomic.load() atomic.store(),您可以在代码中使用它们,这将调用 load() store()隐式。

I created one thread in my main program, thread execution has to stop once the main program will terminate. I am using reader.join(); to terminate the thread execution. But it is not stopping the execution.

I tried with below-mentioned code, I am using thread.join(); function, but it is failed to terminate a thread. And after the main program also my thread is kept executing.

#include <algorithm>
#include <array>
#include <atomic>
#include <mutex>
#include <queue>
#include <cstdint>
#include <thread>
#include <vector>

using namespace std;
using namespace std::chrono;

typedef pair<int, Mat> pairImage;

class PairComp {
public:
    bool operator()(const pairImage& n1, const pairImage& n2) const
    {
        if (n1.first == n2.first)
            return n1.first > n2.first;
        return n1.first > n2.first;
    }
};

int main(int argc, char* argv[])
{
    mutex mtxQueueInput;
    queue<pairImage> queueInput;
    int total = 0;
    atomic<bool> bReading(true);
    thread reader([&]() {
        int idxInputImage = 0;
        while (true) {
            Mat img = imread("img_folder/");
            mtxQueueInput.lock();
            queueInput.push(make_pair(idxInputImage++, img));
            if (queueInput.size() >= 100) {
                mtxQueueInput.unlock();
                cout << "[Warning]input queue size is " << queueInput.size();
                // Sleep for a moment
                sleep(2);
            }
            else {
                mtxQueueInput.unlock();
            }
        }
        bReading.store(false);
    });

    while (true) {
        pair<int, Mat> pairIndexImage;
        mtxQueueInput.lock();
        if (queueInput.empty()) {
            mtxQueueInput.unlock();
            if (bReading.load())
                continue;
            else
                break;
        }
        else {
            // Get an image from input queue
            pairIndexImage = queueInput.front();
            queueInput.pop();
        }
        mtxQueueInput.unlock();
        cv::Mat frame = pairIndexImage.second;

        cv::rectangle(frame, cv::Rect{ 100, 100, 100, 100 }, 0xff);
    }

    cv::imshow("out_image", frame);
    waitKey(1);

    if (total++ == 200)
        break;

    if (reader.joinable()) {
        reader.join();
    }

    return 0;
}

解决方案

thread.join() does not cause the thread to terminate, it waits until the thread ends. It's the responsibility of the thread to end its execution, for example by periodically checking for a certain condition, like a flag.

You already have an atomic flag bReading, which appears to cause the thread to exit.

        if (queueInput.empty()) {
            mtxQueueInput.unlock();
            if (bReading.load())
                continue;
            else
                break;  // thread will exit when queue is empty and bReading == false

So all you need is to set bReading = false in the outer thread before calling thread.join().

bReading = false;
reader.join();

Note that bReading.store(false); inside your thread will have no effect.


Note: you don't need to call atomic.load() and atomic.store(), you can just use them in your code, which will call load() and store() implicitly.

这篇关于如何停止C ++中的线程执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆