我在主程序中创建了一个线程,一旦主程序终止,线程执行就必须停止。我正在使用 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/