请问终止boost::thread的一个问题

Cadillac 2011-01-27 10:42:45
void test ()
{
for (int i = 0 ; i < 10000;++i)
{
Sleep(1);
//POXIS::Sleep(1);
printf("1--%d\n",i);
}
}

std::vector<boost::thread*> vec2;
void createthread()
{
boost::thread thrd1(&test);
thrd1.detach();
vec2.push_back(&thrd1);
}

int main(int argc, char* argv[])
{
std::cout<<boost::thread::hardware_concurrency()<<std::endl;

createthread();

Sleep(1000);
std::cout<<vec2.size()<<std::endl;
for (int i = 0 ; i < vec2.size(); ++i)
{
vec2[i]->interrupt(); //请问这里为什么不对,可以这样终止我的线程么?
std::cout<<"interrupt one "<< vec2.size()<<std::endl;
}
}

我的意思是,希望能在一个函数中创建比较多的线程,这些线程的个数是不可预见的
且每个线程的生命期也是有长有断
但是如果该线程没有终止
我可以手动的在另一个函数中终止该进程
请问我的这种方法为什么会不对呢,运行到我写的注释那里时出问题
...全文
318 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
zhangsongcui 2011-01-28
  • 打赏
  • 举报
回复
这样就对了

#include <iostream>
#include <boost\thread.hpp>
#include <boost\ptr_container\ptr_vector.hpp>

void test()
{
for (int i = 0 ; i < 10000;++i)
{
boost::this_thread::sleep(boost::posix_time::seconds(1));
printf("1--%d\n",i);
}
}

void createthread(boost::ptr_vector<boost::thread>& vec)
{
vec.push_back(new boost::thread(test));
//vec[0].detach();
}

int main(int argc, char* argv[])
{
boost::ptr_vector<boost::thread> vec;
std::cout<<boost::thread::hardware_concurrency()<<std::endl;

createthread(vec);

boost::this_thread::sleep(boost::posix_time::seconds(5));
std::cout << vec.size() << std::endl;
for (size_t i = 0 ; i < vec.size(); ++i)
{
vec[i].interrupt(); //请问这里为什么不对,可以这样终止我的线程么?
std::cout<<"interrupt one "<< vec.size()<<std::endl;
}
system("PAUSE");
}
zhangsongcui 2011-01-28
  • 打赏
  • 举报
回复
我自学boost::thread未久,不知讲得对不对
createthread函数结束时,thrd1析构(线程终止),vec2中存的是野指针。
thrd1应该放到堆里而非栈上,防止其自动析构
晨星 2011-01-28
  • 打赏
  • 举报
回复
你可以看看boost::thread_group;
还有,线程完了别忘了从外面join一下,除非是detach的。
想从外面interrupt的话,需要内外配合。线程中的interrupt_point要用try/catch包起来,捕捉boost::thread_interrupted。
Cadillac 2011-01-28
  • 打赏
  • 举报
回复
明白了,多谢

24,854

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 工具平台和程序库
社区管理员
  • 工具平台和程序库社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧