将参数作为 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);
}
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
只要
sizeof(long) <= sizeof(void*)
就有效,并且long
的每个值都可以表示为void*.
更好的方法是传递变量的地址。您可以从
T*
转换为void*
,然后安全地返回,无需任何假设。This works as long as
sizeof(long) <= sizeof(void*)
, and that every value oflong
can be represented as avoid*
.Better would be to pass the address of the variable. You can cast from a
T*
tovoid*
, and back again safely and without assumption.它与任何类型的类型转换一样合法。关键是,在对参数指向的值进行类型转换之前,无法对它执行任何操作,因此
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?.