【问题标题】:Is it legitimate to pass an argument as void*?将参数传递为 void* 是否合法?
【发布时间】:2010-06-04 09:24:04
【问题描述】:

我刚刚开始学习 pthreads API,正在学习教程here

但是,在pthread_create 的示例程序中,示例程序创建了一个长变量并传递它的值,类型转换为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);
}

【问题讨论】:

  • 所以你的问题是关于强制转换的有效性或传递指针作为 pthread_create() 的第四个参数的有效性?
  • @qrdl:实际上两者兼而有之,但我更感兴趣的是传递 pthread_create 的第四个参数,使编译器认为您实际上是在发送地址。

标签: c pthreads void


【解决方案1】:

这与sizeof(long) &lt;= sizeof(void*) 一样有效,并且long 的每个值都可以表示为void*

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

【讨论】:

  • @Charles sizeof(void)sizeof(void*) 是不同的野兽
【解决方案2】:

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

查看较早的问答When to use a void pointer?

【讨论】:

  • 你是说,void* 的意思是“指向某物的指针”,但“某物”需要先定义才能使用,对吧?
  • @Abel:对。关键是当你想用一个不能给出类型信息的指针做某事时。
猜你喜欢
  • 2012-11-19
  • 2021-11-19
  • 1970-01-01
  • 2017-07-10
  • 1970-01-01
  • 2016-12-17
  • 2016-07-03
  • 2018-01-07
  • 2017-01-14
相关资源
最近更新 更多