[unix]线程返回值

#include "apue.h"
#include 

struct foo {
    int a,b,c,d;
};

void printfoo(const char *s , const struct foo *fp)
{
    printf("%s",s);
    printf(" structure at 0x%lx\n",(unsigned long)fp);
    printf(" foo.a = %d \n",fp->a);
    printf(" foo.b = %d \n",fp->b);
    printf(" foo.c = %d \n",fp->c);
    printf(" foo.d = %d \n",fp->d);

}

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

void * thr_fn2(void *arg)
{
    printf("thread 2 : ID is %lu\n",(unsigned long)pthread_self());
    pthread_exit((void *)0);
}

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)
        err_exit(err,"can't create thread 1");
    err = pthread_join(tid1,(void *)&fp);
    if(err != 0)
        err_exit(err,"can't join with thread 1");
    sleep(1);

    printf("parent starting second thread\n");

    err = pthread_create(&tid2,NULL,thr_fn2,NULL);
    if(err != 0)
        err_exit(err,"can't create thread 2");
    sleep(1);
    printfoo("parent:\n",fp);
    exit(0);

}

返回结果:

thread 1:
 structure at 0x7f955bd38ea0
 foo.a = 1 
 foo.b = 2 
 foo.c = 3 
 foo.d = 4 
parent starting second thread
thread 2 : ID is 140279467448064
parent:
 structure at 0x7f955bd38ea0
 foo.a = 0 
 foo.b = 0 
 foo.c = 1 
 foo.d = 0 

在第一个线程栈上分配的结构体作为返回值返回
会被第二个线程返回时候覆盖
主线程的值发生了变化
实现平台 linux


学无止境不耻下问:https://includestdio.com

你可能感兴趣的:(系统,unix)