2013-05-22 57 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的地址,當你的子線程訪問它時,這個地址會在主線程中增加。