I created one thread in my main program, thread execution has to stop once 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. & after 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;
}
Aucun commentaire:
Enregistrer un commentaire