6

我刚刚开始学习 pthreads API,我正在关注这里的教程

但是,在 的示例程序中pthread_create,示例程序创建一个 long 变量并传递它的值,类型转换为void*。在线程入口函数中,它像 long 一样取消引用它。

这是合法的吗?我知道如果我传递变量的地址t,每个线程都将作用于同一个变量而不是它的副本。我们可以这样做吗,因为它是 avoid*并且编译器不知道我们发送的是什么类型?

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

#define NUM_THREADS     5

void *PrintHello(void *threadid)
{
   long tid;
   tid = (long)threadid;
   printf("Hello World! It's me, thread #%ld!\n", tid);
   pthread_exit(NULL);
}

int main (int argc, char *argv[])
{
   pthread_t threads[NUM_THREADS];
   int rc;
   long t;
   for(t=0; t<NUM_THREADS; t++){
      printf("In main: creating thread %ld\n", t);
      rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t);
      if (rc){
         printf("ERROR; return code from pthread_create() is %d\n", rc);
         exit(-1);
      }
   }
   pthread_exit(NULL);
}
4

2 回答 2

4

它与任何类型的类型转换一样合法。关键是参数指向的值不能做任何事情,直到它被类型转换,因此tid = (long)threadid.

检查较早的问答何时使用 void 指针?.

于 2010-06-04T09:27:26.430 回答
4

只要sizeof(long) <= sizeof(void*), 并且 的每个值long都可以表示为void*.

最好是传递变量的地址。您可以从 a 投射T*void*,然后安全地再次返回,而无需假设。

于 2010-06-04T09:31:22.643 回答