[英]is it possible to terminate a thread with another thread in c++?
我想編寫一個程序,其中許多功能可以同時運行。 我已經弄清楚了,為了做到這一點,我需要使用線程。 在我的程序中,以不同的溫度和速度加熱和旋轉物體的例程必須循環運行一段確定的時間。 時間過去后,我希望該過程繼續進行下一個加熱/旋轉(...)。 我的想法是編寫一個“計時器線程”,它可以某種方式結束當前例程,然后跳到下一個例程。 這可能嗎?
我想大多數方法都將在工作線程和發出停止工作信號的線程之間包含一個共享標志。
因此,您可能會遵循以下原則:
// Use a std::atomic_bool to signal the thread safely
void process_stuff(std::atomic_bool& stop_processing)
{
while(!stop_processing) // do we keep going?
{
// do some measurements or action
std::this_thread::sleep_for(std::chrono::milliseconds(1)); // wait for next action
}
}
在另一個線程的其他地方...
std::atomic_bool stop_processing{false};
// start thread (use std::ref() to pass by reference)
std::thread proc_thread(process_stuff, std::ref(stop_processing));
// wait for some time...
std::this_thread::sleep_for(std::chrono::seconds(3));
stop_processing = true; // signal end
proc_thread.join(); // wait for end to happen
// now create a new thread...
在啟動線程中,通過更改變量stop_processing
的值,您可以向運行中的線程發出停止循環的信號,在這種情況下,該循環會正常結束。
檢查一下:
int main() {
// first thread
auto thread1 = std::make_unique<std::thread>([]() {
std::this_thread::sleep_for(std::chrono::seconds(1));
std::cout << "over\n";
});
// disposing to second thread
std::thread([thread2 = std::move(thread1)](){
thread2->join();
}).detach();
//spinning a new thread
thread1.reset(new std::thread([]() {
std::this_thread::sleep_for(std::chrono::seconds(1));
std::cout << "next over\n";
}));
thread1->join();
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.