Forma adecuada de terminar un hilo en c ++
Estoy aprendiendo sobre multihilo y escribí este código:
#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;
}
Como puede ver, el hilo 'keep_moving' cuenta de 0 a 20 en 20 segundos y luego notifica al hilo 'wake_me_up' que imprime "Estoy aquí" y luego termina. Después de notificar al hilo, el hilo 'keep_moving' también termina.
Por favor, dígame si estoy terminando los hilos de manera adecuada. Cuando ejecuto este código, recibo el siguiente mensaje:
terminate called without an active exception
I'm here
terminate called recursively
Aborted
Gracias.