关于 pthreads 和 pthreads 的问题指针
下面是一个经常看到的线程创建代码的例子。 pthread_create 使用了很多指针/地址,我想知道为什么会这样。
pthread_t threads[NUM_THREADS];
long t;
for(t=0; t<NUM_THREADS; t++){
rc = pthread_create(&threads[t], NULL, &someMethod, (void *)t);
}
使用“&”有什么主要优点或区别吗?引用变量数组“threads”以及“someMethod”(而不是仅“threads”和“someMethod”)?另外,为什么“t”通常作为 void 指针传递,而不是仅传递“t”?
Here is an example of thread creation code that is often seen. pthread_create uses a lot of pointers/addresses and I was wondering why this is so.
pthread_t threads[NUM_THREADS];
long t;
for(t=0; t<NUM_THREADS; t++){
rc = pthread_create(&threads[t], NULL, &someMethod, (void *)t);
}
Is there a major advantage or difference for using the '&' to refer to the variable array 'threads' as well as 'someMethod' (as opposed to just 'threads' and just 'someMethod')? And also, why is 't' usually passed as a void pointer instead of just 't'?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要将指向
pthread_t
变量的指针
传递给pthread_create
。&threads[t]
和threads+t
实现了这一点。threads[t]
没有。pthread_create
需要一个指针,以便可以通过它返回一个值。someMethod
是第三个参数的合适表达式,因为它是函数的地址。我认为&someMethod
是冗余等价的,但我不确定。您将
t
转换为void *
,以便将long
插入到void *
中。我认为long
不能保证适合void *
。即使存在保证,这也绝对是一个次优的解决方案。为了清晰起见,您应该传递一个指向t
的指针(&t
,无需转换)并确保与预期的void *
兼容。不要忘记相应地调整someMethod
。You need to pass a
pointer
to apthread_t
variable topthread_create
.&threads[t]
andthreads+t
achieve this.threads[t]
does not.pthread_create
requires a pointer so it can return a value through it.someMethod
is a suitable expression for the third argument, since it's the address of the function. I think&someMethod
is redundantly equivalent, but I'm not sure.You are casting
t
tovoid *
in order to jam along
into avoid *
. I don't think along
is guaranteed to fit in avoid *
. It's definitely a suboptimal solution even if the guarantee exists. You should be passing a pointer tot
(&t
, no cast required) for clarity and to ensure compatibility with the expectedvoid *
. Don't forget to adjustsomeMethod
accordingly.