我遇到了pthread_create的問題。在這個測試中,我創建了一個整數數組,然後嘗試將它們用作必須在線程中執行的函數的參數。pthread_create更改數組的值
這是我創建索引:
int *indexes = (int *) malloc(sizeof(int)*threadNumber);
int i;
for (i = 0; i < threadNumber; i++){
indexes[i] = i;
}
而這正是我創建的線程:
int i;
for (i = 0; i < threadNumber; i++){
printf("%i %i ", i, indexes[i]);
}
for (i = 0; i < threadNumber; i++){
printf("%i %i ", i, indexes[i]);
pthread_create(sons + sizeof(pthread_t)*i, NULL, sonSimulation, (void *) &indexes[i]);
}
第一個printf打印以下內容:
0 0 1 1 2 2 3 3 4 4
第二一個應該打印相同的輸出,打印此:
0 0 1 1 2 2 3 3 4 23154684
每次我執行代碼時,最後一個數字都會改變。 我無法解決這個問題。任何建議?
(sonSimulation只是打印參數)
'sons'是什麼?它是如何聲明的?你爲什麼不使用普通的數組索引呢?此外,你是線程不覆蓋他們得到的指針? –
請發佈[MCVE](http://stackoverflow.com/help/mcve)。試試'sons [i]'或'sons + i'而不是'sons + sizeof(pthread_t)* i'。另外,請發佈'sonSimulation'功能。 –
[請參閱爲什麼不投射](http://stackoverflow.com/q/605845/2173917)'malloc()'和'C'中的系列的返回值。 –