1
int pthread_join(pthread_t thread, void **retval);
void pthread_exit(void *retval);

pthread_exit 呼び出しでは、渡す必要がある値へのポインターを渡します。そして、pthread_join では、マニュアル ページによると、ポインターへのポインターである必要があります。期待される結果を取得します。しかし、以下に示すように int を使用すると、ガベージ値が取得されます。この実装は正しいですか?

void * sum(void * id)
{
      int n = *(int *)id;
      pthread_exit((void *)&n);
}
void main()
{
      pthread_t t1;
      int *s;
      s = malloc(sizeof(int));
      int num;
      num=5;
      pthread_create(&t1,NULL,sum,(void *)&num);
      pthread_join(t1,(void **)&s);
      printf("returned %d \n",*s);
      pthread_exit(NULL);
}
4

1 に答える 1

4

スタックから値を返さないでください。のマニュアルページからpthread_exit

The value pointed to by  retval  should  not  be  located  on  the  calling
thread's  stack,  since  the contents of that stack are undefined after the
thread terminates.
于 2014-12-01T14:10:53.473 に答える