【发布时间】:2013-12-04 23:13:36
【问题描述】:
这是我的程序,只是为了找出 pthread_exit 和从线程返回之间的区别。
struct foo{
int a,b,c,d;
~foo(){cout<<"foo destructor called"<<endl;}
};
//struct foo foo={1,2,3,4};
void printfoo(const char *s, const struct foo *fp)
{
cout<<s;
cout<<"struct at 0x"<<(unsigned)fp<<endl;
cout<<"foo.a="<<fp->a<<endl;
cout<<"foo.b="<<fp->b<<endl;
cout<<"foo.c="<<fp->c<<endl;
cout<<"foo.d="<<fp->d<<endl;
}
void *thr_fn1(void *arg)
{
struct foo foo={1,2,3,4};
printfoo("thread1:\n",&foo);
pthread_exit((void *)&foo);
//return((void *)&foo);
}
int main(int argc, char *argv[])
{
int err;
pthread_t tid1,tid2;
struct foo *fp;
err=pthread_create(&tid1,NULL,thr_fn1,NULL);
if(err!=0)
cout<<"can't create thread 1"<<endl;
err=pthread_join(tid1,(void **)&fp);
if(err!=0)
cout<<"can't join with thread 1"<<endl;
exit(0);
}
在“*thr_fn1”线程函数中,我创建了一个对象 foo。
据网站pthread_exit vs. return 当我使用“return((void *)&foo);”退出线程函数“thr_fun1()”时它应该调用对象 foo 的析构函数,但是当我调用“pthread_exit((void *)&foo);”时它不应该调用析构函数从函数“thr_fun1()”返回到 main。
但在这两种情况下都使用“return((void *)&foo);”或“pthread_exit((void *)&foo);”函数“thr_fun1()”中的本地对象“foo”被调用。
这不是我猜的行为。只能在“return((void *)&foo);”中调用析构函数仅限大小写。
如果我错了,请验证我?
【问题讨论】:
标签: c++ multithreading