[英]How to stop the thread execution in C++
我在主程序中創建了一個線程,一旦主程序終止,線程執行必須停止。 我正在使用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()
。
我不知道停止thread
的內置可能性。 由於您的線程中嵌入了endless-loop
,因此它不會隨時停止。
std::thread::join
不會終止您的線程。 當需要時,您必須實現一些東西來結束循環。
thread
必須退出時,將bool
變量設置為false
。 例如while(run)
或類似的東西; 為了簡單起見,您還可以使用std::atomic<bool>
std::condition_variable
您現在所要做的是,在main-thread
中等待thread
終止。 由於std::thread::join
不會終止您的thread
,因此您的main-thread
將永遠執行。
注意:當您選擇實施bool
解決方案時。 您應該使用mutex
或類似方法保護此bool
。
感謝您的評論。 因為我不想指出每個人都可以boost
,但是您提到了它。 在此處查找信息。
這個問題是不是與join
其中(BTW)並不意味着可以用來停止或終止線程。
您的線程正在執行的函數包含一個while(true)
,它將永遠不會終止,因為它只能休眠並解鎖鎖,沒有別的。
這意味着將永遠不會調用bReading.store
,因此在主線程循環中,您總是會經過
if (bReading.load())
continue;
意思是main
也將永遠執行。
std::join
用於從線程中等待另一個線程完成其工作。 當你做thread1.join()
從main
線程什么情況是, main
會等到 thread1
已完成執行任何其他指令之前執行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.