2013-01-04 34 views
2

如何將p_thread的id保存到數組中?如何將pthread_t id保存到數組

int i; 
pthread_t t[N]; 
float arrayId[N]; 


for (i = 0; i < N; i++) { 
    pthread_create(&t[i], NULL, f, (void *) &i); 
    printf("creato il thread id=%lu\n", t[i]); 
    arrayId[i] = t[i]; 
    printf("a[%d]=%f\n", i, arrayId[i]); 
} 

我可以打印,但我沒能救...

我得排序這個數組,然後我就必須先執行由ID訂購的所有線程

+0

你用'save'表示什麼意思?因爲't'已經包含了每個線程ID,所以它被'保存'了,那麼爲什麼你需要另一個數組呢?即使你願意,使用float也沒有意義。 – stijn

+1

看看這個http://stackoverflow.com/questions/1759794/how-to-print-pthread-t – benjarobin

回答

2

所有線程都會收到相同的值i,因爲您是通過值(同一地址)傳遞它的。 這應該修復它:

int i; 
pthread_t t[N]; 
float arrayId[N]; 

int indexes[N]; 

for (i = 0; i < N; i++) { 
    indexes[i] = i; 
    pthread_create(&t[i], NULL, f, (void *) &indexes[i]); 
    printf("creato il thread id=%lu\n", t[i]); 
    arrayId[i] = t[i]; 
    printf("a[%d]=%f\n", i, arrayId[i]); 
} 
1
I'll have to sort this array and then i'll have to execute first all the thread 
ordered by id 

pthread_create作爲人國家已經執行一個線程:

The pthread_create() function starts a new thread in the calling process. 

所以你的循環已經開始N個線程。你也不能指定線程標識符,它們在創建線程時返回。