将参数传递为void*是否合法?

Adi*_*gal 6 c pthreads void

我刚开始学习pthreads API,我在这里遵循教程

但是,在一个示例程序中pthread_create,示例程序创建一个long变量并传递其值,将其类型化为void*.在线程入口函数中,它解除它就像一个long.

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

#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);
}
Run Code Online (Sandbox Code Playgroud)

GMa*_*ckG 4

只要sizeof(long) <= sizeof(void*),并且 的每个值都long可以表示为 a ,该方法就有效void*

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