我正在使用 boost 并尝试创建一个基本thread_group来执行他们的任务并退出。这是我的代码的样子:
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;
}
我从两个线程开始,在两个线程完成其工作后陷入无限循环。如下所示:
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
我哪里出错了?
你的boost::thread t[]
和boost::thread_group threads;
之间没有关系。
所以t[iterator].interrupt();
对threads.create_thread(boost::bind(&InputThread)) ;
生成的线程没有影响。
而是做:
std::vector<boost::thread *> thread_ptrs;
// ...
thread_ptrs.push_back(threads.create_thread(boost::bind(&InputThread)));
// ...
thread_ptrs[iterator].interrupt();
旁白:"迭代器"这个名称通常用于类型,并且迭代的值很差。 对此值使用 i
或其他一些惯用名称。