如何在C++中停止线程执行

Gag*_*eep 1 c++ multithreading mutex pthreads c++11

我在主程序中创建了一个线程,一旦主程序终止,线程执行就必须停止。我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;
}
Run Code Online (Sandbox Code Playgroud)

rus*_*tyx 6

thread.join()不会导致线程终止,它会等待直到线程结束。线程有责任结束其执行,例如通过定期检查特定条件(如标志)。

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

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

因此,所有你需要的是一组bReading = false 外螺纹之前调用thread.join()

bReading = false;
reader.join();
Run Code Online (Sandbox Code Playgroud)

请注意,bReading.store(false);在您的线程内将不起作用。


注意:你不需要调用atomic.load()and atomic.store(),你可以在你的代码中使用它们,它会隐式调用load()and store()