我正在使用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
我哪里错了?
答案 0 :(得分:1)
您的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();
除此之外:名称“iterator”通常用于类型,并且迭代结果值很小。使用i
或其他惯用名称作为此值。