对pthread_create()中的参数感到困惑 [英] Confused about the argument in pthread_create()

查看:119
本文介绍了对pthread_create()中的参数感到困惑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题:为什么不将& i作为最后一个参数传递给pthread_create()?相反,他创建了一个数组来保存相同的东西....

My question :why not just pass &i as the last argument to pthread_create()? instead he create a array to hold the same thing....

#define THREAD_CT 2  /* bump this up a few numbers if you like */

void *print_stuff(void *ptr) {
  int i, id= * (int *) ptr;

  for (i= 0; i < 5; i++) {
    printf("Thread %d, loop %d.\n", id, i);
    sleep(rand() % 2);  /* sleep 0 or 1 seconds */
  }

  printf("Thread %d exiting.\n", id);

  return NULL;
}

int main(void) {
  pthread_t tids[THREAD_CT];
  int i, ids[THREAD_CT];

  for (i= 0; i < THREAD_CT; i++) {
    ids[i]= i;
    pthread_create(&tids[i], NULL, print_stuff, &ids[i]);
    printf("Main thread created thread %d (ID %ld).\n", i, tids[i]);
  }

  for (i= 0; i < THREAD_CT; i++) {
    pthread_join(tids[i], NULL);
    printf("Main thread reaped thread %d (ID %ld).\n", i, tids[i]);
  }

  return 0;
}

推荐答案

为什么不将& i作为最后一个参数传递给pthread_create()?

why not just pass &i as the last argument to pthread_create()?

因为这样做,所有线程将共享地址i,并且线程之间将发生数据争用.

Because if you do that all threads will share the address i and there will be data race between threads.

另一种方法是将值强制转换为:

The alternative is to cast the value like:

pthread_create(&tids[i], NULL, print_stuff, (void *)i);

但是这个整数到指针的转换具有实现定义的行为.所以现在拥有它可能是最好的方法

But this integer to pointer conversion has implementation-defined behaviour. So the way you have it now is probably the best way

还请注意,rand()不是线程安全的.

Also note that rand() is not thread-safe.

这篇关于对pthread_create()中的参数感到困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆