2013-05-22 55 views
0

我与并行线程和下面的代码实验的功能:参数传递在pthread_create

#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 

为什么每一个“我是线索在索引“打印索引高于它应该打印?

回答

2

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