J'utilise boost et essaye de créer un groupe de threads de base qui exécutera leurs tâches et quittera. Voici ce que mon code ressemble à:boost thread_group boucle infinie
boost::thread_group threads;
void InputThread()
{
int counter = 0;
while(1)
{
cout << "iteration #" << ++counter << " Press Enter to stop" << endl;
try
{
boost::this_thread::sleep(boost::posix_time::milliseconds(500));
}
catch(boost::thread_interrupted&)
{
cout << "Thread is stopped" << endl;
return;
}
}
}
int main()
{
int iterator;
char key_pressed;
boost::thread t[NUM_THREADS];
for(iterator = 0; iterator < NUM_THREADS; iterator++)
{
threads.create_thread(boost::bind(&InputThread)) ;
cout << "iterator is: " << iterator << endl;
// Wait for Enter to be pressed
cin.get(key_pressed);
// Ask thread to stop
t[iterator].interrupt();
}
// Join all threads
threads.join_all();
return 0;
}
J'ai commencé avec deux fils et chute dans une boucle infinie après que les deux fils sont faits avec leur emploi. Quelque chose comme ci-dessous:
iterator is: 0
iteration #1 Press Enter to stop
iteration #2 Press Enter to stop
iterator is: 1
iteration #1 Press Enter to stop
iteration #3 Press Enter to stop
iteration #2 Press Enter to stop
iteration #4 Press Enter to stop
iteration #3 Press Enter to stop
iteration #5 Press Enter to stop
iteration #4 Press Enter to stop
iteration #6 Press Enter to stop
iteration #5 Press Enter to stop
iteration #7 Press Enter to stop
^C
Où je vais mal?
Merci, cela résout le problème. Je vais avoir besoin d'une meilleure compréhension de thread_group cependant. –
@ user2816953 Si vous êtes satisfait de la réponse, veuillez augmenter votre vote et/ou accepter la réponse en conséquence. –
J'ai déjà accepté la réponse mais je n'ai toujours pas assez de réputation pour upvote. Je viens de m'inscrire il y a deux jours. Quand j'y serai, je vous rendrai la réponse en votant :) –