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