【问题标题】:Confused about the argument in pthread_create()对 pthread_create() 中的参数感到困惑
【发布时间】:2015-12-05 19:26:07
【问题描述】:

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

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

【问题讨论】:

    标签: c multithreading pthreads pthread-join


    【解决方案1】:

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

    因为如果您这样做,所有线程将共享地址i,并且线程之间将存在数据竞争。

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

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

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

    还要注意rand() 不是线程安全的。

    【讨论】:

    • 你的回答给我留下了深刻的印象@Bluemoon :-)
    • 还有一个问题:为什么 id= * (int *) ptr 使用 * (int *)??@BlueMoon
    • @overloading ptrvoid * 类型,即通用指针。它不能被直接取消引用,因为您不知道它指向的实际指针类型的底层大小(它可以是char *long * 或任何其他数据指针)。所以你需要在取消引用之前将其转换为正确的类型。
    猜你喜欢
    • 2015-09-05
    • 2020-12-06
    • 1970-01-01
    • 2021-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-05
    相关资源
    最近更新 更多