将类型转换指针传递给pthread_join

问题描述 投票:0回答:1

我有一个分配,我在C中使用线程,并且与很多人类似,由于pthread_join的第二个参数类型为void**而导致错误,然后经过一番研究,我弄清楚了类型铸造工程。这是我正在谈论的示例:

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>

void *callback(void *arg){
    sleep(2);
    pthread_exit("done !!\n");
}

int main(){
  pthread_t th;
  void *val;

  pthread_create(&th, NULL, callback, NULL);
  pthread_join(th, &val);
  printf("%s", (char*)val);

  return EXIT_SUCCESS;
}

并且这按预期工作,但随后我感到好奇,并尝试声明一个char *val,然后将其强制转换的版本传递给pthread_join函数,如下所示:

int main(){
  pthread_t th;
  char *val;

  pthread_create(&th, NULL, callback, NULL);
  pthread_join(th, (void*)&val);
  printf("%s", val);

  return EXIT_SUCCESS;
}

这很好,但是我不明白在此版本的代码中类型转换的工作方式。谁能解释一下?

c casting pthreads
1个回答
2
投票

第一个密码正确,第二个密码不正确。您将避免使用它,因为char *void *的表示形式很可能兼容。

© www.soinside.com 2019 - 2024. All rights reserved.