我正在学习多线程,我写了以下代码:
#include <iostream>
#include <mutex>
#include <thread>
#include <string>
#include <chrono>
#include <condition_variable>
int distance = 20;
int distanceCovered = 0;
std::condition_variable cv;
std::mutex mu;
void keep_moving(){
while(true){
std::cout << "Distance is: " << distanceCovered << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
distanceCovered++;
if(distanceCovered == distance){
cv.notify_one();
std::terminate();
}
}
}
void wake_me_up()
{
std::unique_lock<std::mutex> ul(mu);
cv.wait( ul, []{ return distanceCovered==distance; }); // protects the lines of code below
std::cout << "I'm here" << std::endl;
std::terminate();
}
int main() {
std::thread driver(keep_moving);
std::thread wake_me(wake_me_up);
driver.join();
wake_me.join();
system("pause");
return 0;
}
从代码中可以看到,'keep_moving'线程在20秒内从0-20计数,然后通知'wake_me_up'线程打印"I'm here"并终止。通知完线程后,'keep_moving'线程也终止。
请告诉我是否以正确的方式终止了线程。运行代码后,会得到以下消息:
terminate called without an active exception
I'm here
terminate called recursively
Aborted
谢谢你。
std::terminate
?因为你 真的 不应该这样做。 - Rob K