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

发布于 2024-09-04 01:20:24 字数 1045 浏览 5 评论 0原文

我刚刚开始学习 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);
}

I have just started learning pthreads API and I am following the tutorial here

However, in an example program of pthread_create, the sample program creates a long variable and passes its value, typecasted as void*. In the thread entry function, it dereferences it just like a long.

Is this legit?
I understand if I pass the address of variable t, every thread would be acting on the same variable and not on a copy of it. Can we do this because it's a void* and the compiler has no idea about what type we are sending?

#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);
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

烟沫凡尘 2024-09-11 01:20:24

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

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

This works as long as sizeof(long) <= sizeof(void*), and that every value of long can be represented as a void*.

Better would be to pass the address of the variable. You can cast from a T* to void*, and back again safely and without assumption.

暖树树初阳… 2024-09-11 01:20:24

它与任何类型的类型转换一样合法。关键是,在对参数指向的值进行类型转换之前,无法对它执行任何操作,因此 tid = (long)threadid

查看旧版问答何时使用 void 指针?

It's as legitimate as any kind of typecasting. The point is that nothing can be done with the value the argument points to, until it is typecast, hence tid = (long)threadid.

Check the older Q&A When to use a void pointer?.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文