为什么pthread返回的值与传递给线程函数的值不同?

时间:2017-09-01 09:13:32

标签: c pthreads posix

我理解pthread_join manual我的程序应该输出我提供给print_xs的相同值,但获得的输出是:

Message from printxs 11131 a
Message from printxs 11234 b
32766 -16
32766 0

该计划:

#include<stdio.h>
#include<pthread.h>

typedef struct paramsThread{
        char c;
        int count;
} threadPara;

void* print_xs(void* unused){
        threadPara *tp = (threadPara *)unused;
        int i=tp->count;

        printf("Message from printxs %d %c\n", tp->count, tp->c);
        return (void*)tp;
}

int main(){
        pthread_t thread1, thread2;
        threadPara t1,t2,t3,t4;
        t1.c = 'a';
        t2.c = 'b';
        t1.count = 11131;
        t2.count = 11234;
        t3.count=0;
        pthread_create(&thread1, NULL, &print_xs, &t1);
        pthread_create(&thread2, NULL, &print_xs, &t2);
        pthread_join(thread1,(void*)&t3);
        printf("%d %d\n", t3.count, t3.c);
        pthread_join(thread2,(void*)&t4);
        printf("%d %d\n", t4.count, t4.c);
        return 0;
}

有人可以解释为什么会这样吗?

2 个答案:

答案 0 :(得分:5)

如果你read a pthread_join reference or manual page,你会看到第二个参数是一个指向的指针。这是一种在C中模拟按引用传递的方法。

线程函数返回的指针被复制到另一个指针。

解决方案是使用t3t4的指针代替:

threadPara t1, t2;
threadPara *t3, *t4;

// ...

pthread_join(thread1,(void**)&t3);  // Pass pointer to the pointer, emulating pass by reference
printf("%d %d\n", t3->count, t3->c);
pthread_join(thread2,(void**)&t4);
printf("%d %d\n", t4->count, t4->c);

如果您打印指针或使用调试器,那么您会看到t3指向t1(即t3 == &t1),t4指向t2和{{1}}。

答案 1 :(得分:0)

线程函数返回一个地址void*

pthread_join()收到的地址,其中2 nd 参数(void**指向。< / p>

所以要在代码中使用它而不是

        pthread_join(thread1, (void*)&t3);

DO

        {
          void * pv;
          pthread_join(thread1, &pv);
          if (NULL != pv)
          {
            t3 = *((threadPara*) pv);
          }
        }

作为旁注:在C中, no 需要强制转换为void - 来自/到其他指针的指针,所涉及的指针会被隐式转换。

所以这段代码

void* print_xs(void* unused){
    threadPara *tp = (threadPara *)unused;
    int i=tp->count;

    printf("Message from printxs %d %c\n", tp->count, tp->c);
    return (void*)tp;
}

很可能是这样写的:

void* print_xs(void* unused){
    threadPara *tp = unused;
    int i=tp->count;

    printf("Message from printxs %d %c\n", tp->count, tp->c);
    return tp;
}