随笔-6  评论-2  文章-1  trackbacks-0
一. 线程启动
    线程的启动由传递一个没有构造函数的Callable类,之后复制到内存,由最新的线程调用.
struct callable
{
    
void operator()();
};
如果该类必须不可复制,那么可以用boost::ref传递一个Callable对象的引用到构造中.
boost::thread copies_are_safe()
{
    callable x;
    
return boost::thread(x); //参数为X的一份拷贝
// x is destroyed, but the newly-created thread has a copy, so this is OK 
boost::thread oops()
{
    callable x;
    
return boost::thread(boost::ref(x)); //参数为X的引用
// x is destroyed, but the newly-created thread still has a reference
  
// this leads to undefined behaviour
线程可以用一个函数或callable对象为参数构造,用boost::bind来实现
void find_the_question(int the_answer);

boost::thread deep_thought_2(boost::bind(find_the_question,
42));
void print();
boost::thread t=boost::thread(&print);

二.线程接合与脱离
当被销毁时,线程称为脱离(detached),当线程为脱离(detached)时,线程继续执行直到构造函数中函数或callable对象执行完毕,或程式终止.
void print();
boost::thread t(
&print);
t.join();
//线程销毁
t.join();//线程已经失效,t不指向任何线程,无作用
std::cout<<boolalpha<<t.joinable()<<std::endl;//print false statement

线程的脱离可以明确调用boost::detach()函数,这种情况下线程为非现脱离线程(now-detached thread),变为非线程(Not-a-Thread).
boost::thread::join() //如果线程为中断(interrupted),引发boost::thread_interrupted异常.
boost::thread::detach() //不引发异常,如果线程不脱离,线程析构时调用.



posted on 2009-01-22 10:01 L'双鱼 阅读(1923) 评论(0)  编辑 收藏 引用

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理