c++ - C++中如何停止线程的执行

标签 c++ multithreading c++11 pthreads mutex

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

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

#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() 不会导致线程终止,它会一直等到线程结束。线程有责任结束其执行,例如通过定期检查特定条件(如标志)。

您已经有一个 atomic 标志 bReading,它似乎会导致线程退出。

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

因此,您只需在调用 thread.join() 之前设置 bReading = false 外线程

bReading = false;
reader.join();

请注意,您线程中的 bReading.store(false); 将无效。


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

关于c++ - C++中如何停止线程的执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55824719/

相关文章:

c++ - 按值返回堆栈上的变量是否针对移动进行了优化?

c++ - 合并排序中的递归行为不当

c++ - 在 C 中截断 double 而不进行舍入

java - 等待/通知 vs sleep /中断 vs ReentrantLock.Condition

c++ - 暂停 std::thread 直到函数完成

c++ - 有没有办法设计这个 "static class"使其线程安全?

c++ - 如何将包含十六进制值的 unsigned char* 数组写入 python 文件

c++ - 'int [0]' c++ 的初始值设定项太多

java - 多线程环境下的单例模式

python - 尝试将图像从 QThread 发送到 PyQt 中的主线程或其他线程