I am using boost and trying to create a basic thread_group that will perform their tasks and exit. Here's what my code looks like:
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;
}
I started with two threads and fall in an infinite loop after both the threads are done with their jobs. Something like below:
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
Where am I going wrong?
There's no relationship drawn between your boost::thread t[]
and boost::thread_group threads;
.
So t[iterator].interrupt();
has no effect on the threads spawned by threads.create_thread(boost::bind(&InputThread)) ;
.
Instead do:
std::vector<boost::thread *> thread_ptrs;
// ...
thread_ptrs.push_back(threads.create_thread(boost::bind(&InputThread)));
// ...
thread_ptrs[iterator].interrupt();
Aside: the name "iterator" is often used for types and makes a poor value to iterate over. Use i
or some other idiomatic name for this value.