gpt4 book ai didi

对 pthread_create() 中的参数感到困惑

转载 作者:太空宇宙 更新时间:2023-11-04 06:21:26 24 4
gpt4 key购买 nike

我的问题:为什么不将 &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;
}

最佳答案

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

因为如果这样做,所有线程都将共享地址 i,并且线程之间会发生数据竞争。

另一种方法是像这样转换值:

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

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

另请注意,rand() 不是线程安全的。

关于对 pthread_create() 中的参数感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34109827/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com