C 在for循环中创建线程:所有线程传递相同的;我";价值

C 在for循环中创建线程:所有线程传递相同的;我";价值,c,multithreading,pthreads,C,Multithreading,Pthreads,使用这里的建议()我写了以下内容: int threads_count = 2; pthread_t *threads = calloc(threads_count, sizeof(pthread_t)); int j; for(j = 0; j < threads_count; j++) { int thread_number = j; int status = pthread_create(&threads[j], NULL, &my_func, (vo

使用这里的建议()我写了以下内容:

int threads_count = 2;
pthread_t *threads = calloc(threads_count, sizeof(pthread_t));
int j;
for(j = 0; j < threads_count; j++) {
    int thread_number = j;
    int status = pthread_create(&threads[j], NULL, &my_func, (void *) &thread_number);
}
不幸的是,出于我不理解的原因,这会导致每个线程都有线程编号(而不是ID)2

任何建议都将不胜感激

编辑:根据答案的建议,我制作了一个对应int的全局数组,并从for循环中以&arr[I]的形式传递引用。问题如下:

for(j = 0; j < threads_count; j++) {
    int thread_number = j;
    int status = pthread_create(&threads[j], NULL, &my_func, (void *) &thread_number);
}
(将
thread\u number
的值作为
void*
传递),然后像这样取消引用它:

void *my_func(void *thread) {
    int thread_no = (int)thread;
    pthread_t thread_id = pthread_self();
    printf("Thread number: %i\nThread ID: %u\n", thread_no, thread_id);

    ...
}
但是这不是最好的方法,因为不建议在
int
void*
之间混淆(不仅是
int
void*
的指针,还有任何类型的非指针类型的指针)

更好的方法是为每个线程使用一些全局结构,并将该结构的地址作为
void*
参数传递给
my_func

for(j = 0; j < threads_count; j++) {
    int thread_number = j;
    int status = pthread_create(&threads[j], NULL, &my_func, (void *) thread_number);
}
void *my_func(void *thread) {
    int thread_no = (int)thread;
    pthread_t thread_id = pthread_self();
    printf("Thread number: %i\nThread ID: %u\n", thread_no, thread_id);

    ...
}