参数传递给pthread_create中的函数

时间:2013-05-22 04:32:09

标签: c pthreads

我正在尝试使用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

为什么每个“我是索引处的线程”打印的索引高于应该打印的索引?

1 个答案:

答案 0 :(得分:2)

您正在传递循环变量i的地址,当您的子线程访问它时,它会在主线程中递增。