메인 프로그램에 스레드 하나를 만들었는데, 메인 프로그램이 종료되면 스레드 실행을 중지해야합니다. 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
따라서 호출하기 전에 bReading = false
외부 스레드 에 설정 하기 만하면 thread.join()
됩니다.
bReading = false;
reader.join();
참고 bReading.store(false);
스레드 내부에 아무런 영향을주지 않습니다.
참고 :이 호출 할 필요는 없습니다 atomic.load()
그리고 atomic.store()
당신은 호출하는 코드에서 사용할 수 있습니다, load()
그리고 store()
암시.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다