這裏是我的程序只是爲了找到pthread_exit和線程返回之間的區別。pthread_exit vs posix線程返回
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 當我退出線程函數 「thr_fun1()」 使用 「返回((無效*)&富);」它應該調用對象foo的析構函數,但是當我調用「pthread_exit((void *)& foo)時,它不應該調用析構函數;」從函數「thr_fun1()」返回到main。
但是在兩種情況下都使用「return((void *)& foo);」或「pthread_exit((void *)& foo);」函數「thr_fun1()」中的本地對象「foo」正在被調用。
這不是我猜測的行爲。析構函數只能在「return((void *)& foo)中調用;」只有情況。
請確認我是否錯了?
我改變了問題。請在任何編輯器中編譯並回復。 –
「其他不好的問題」包括這樣的混亂,例如沒有釋放由以這種方式被終止的線程獲取/擁有的同步對象(互斥體等)的所有權。 – Bukes