Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pthread_exit vs return in posix thread

Here is my program just to find the difference between pthread_exit and return from a thread.

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);
}

In "*thr_fn1" thread function I created an object foo.

According to the site pthread_exit vs. return when I exit the thread function "thr_fun1()" using "return((void *)&foo);" it should call the destructor for the object foo, but it should not call the destructor when I call "pthread_exit((void *)&foo);" to return to main from function "thr_fun1()".

But in both the cases using "return((void *)&foo);" or "pthread_exit((void *)&foo);" the local object "foo" in function "thr_fun1()" is getting called.

This is not the behaviour I guess. Destructor should be called only in "return((void *)&foo);" case only.

Please verify me if I am wrong?

like image 227
Santosh Sahu Avatar asked Mar 20 '26 17:03

Santosh Sahu


1 Answers

Your code has a serious problem. Specifically, you're using a local variable as the exit value for pthread_exit():

void *thr_fn1(void *arg)
{
    struct foo foo={1,2,3,4};
    printfoo("thread1:\n",&foo);
    pthread_exit((void *)&foo);
    //return((void *)&foo);
}

Per the Pthreads spec, "After a thread has terminated, the result of access to local (auto) variables of the thread is undefined."

Therefore, returning the address of a stack-allocated variable from your thread function as the thread exit value (in your case, pthread_exit((void *)&foo) ) will cause problems for any code that retrieves and attempts to dereference this address.

like image 146
Bukes Avatar answered Mar 22 '26 06:03

Bukes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!