我的问题:为什么不将& 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
发布评论