关于 pthreads 和 pthreads 的问题指针

发布于 2024-12-05 19:00:11 字数 390 浏览 0 评论 0原文

下面是一个经常看到的线程创建代码的例子。 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 技术交流群。

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

发布评论

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

评论(1

优雅的叶子 2024-12-12 19:00:11
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
    void *(*start_routine)(void*), void *arg);

您需要将指向 pthread_t 变量的指针传递给pthread_create&threads[t]threads+t 实现了这一点。 threads[t] 没有。 pthread_create 需要一个指针,以便可以通过它返回一个值。

someMethod 是第三个参数的合适表达式,因为它是函数的地址。我认为 &someMethod 是冗余等价的,但我不确定。

您将 t 转换为 void *,以便将 long 插入到 void * 中。我认为 long 不能保证适合 void *。即使存在保证,这也绝对是一个次优的解决方案。为了清晰起见,您应该传递一个指向 t 的指针(&t,无需转换)并确保与预期的 void * 兼容。不要忘记相应地调整 someMethod


pthread_t threads[NUM_THREADS];
long t;
for (t=0; t<NUM_THREADS; t++) {
    rc = pthread_create(&threads[t], NULL, someMethod, &t);
}
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
    void *(*start_routine)(void*), void *arg);

You need to pass a pointer to a pthread_t variable to pthread_create. &threads[t] and threads+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 to void * in order to jam a long into a void *. I don't think a long is guaranteed to fit in a void *. It's definitely a suboptimal solution even if the guarantee exists. You should be passing a pointer to t (&t, no cast required) for clarity and to ensure compatibility with the expected void *. Don't forget to adjust someMethod accordingly.


pthread_t threads[NUM_THREADS];
long t;
for (t=0; t<NUM_THREADS; t++) {
    rc = pthread_create(&threads[t], NULL, someMethod, &t);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文