我正在试验 pthreads 和以下代码:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void* print_thread_num(void *index);
int main(int argc, char** argv) {
int i;
pthread_t threads[3];
for (i = 0; i < 3; i++) {
void *index = &i;
printf("Creating thread %d\n", i);
pthread_create(&threads[i], NULL, print_thread_num, index);
}
pthread_exit(NULL);
}
void* print_thread_num(void *index) {
int i = *(int*)index;
printf("I am the thread at index %d\n", i);
pthread_exit(NULL);
}
我得到下面的输出:
Creating thread 0
Creating thread 1
I am the thread at index 1
Creating thread 2
I am the thread at index 2
I am the thread at index 3
为什么每个“我是索引处的线程”打印的索引都高于它应该打印的索引?