2015-06-22 124 views
1

我遇到了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只是打印參數)

+2

'sons'是什麼?它是如何聲明的?你爲什麼不使用普通的數組索引呢?此外,你是線程不覆蓋他們得到的指針? –

+1

請發佈[MCVE](http://stackoverflow.com/help/mcve)。試試'sons [i]'或'sons + i'而不是'sons + sizeof(pthread_t)* i'。另外,請發佈'sonSimulation'功能。 –

+1

[請參閱爲什麼不投射](http://stackoverflow.com/q/605845/2173917)'malloc()'和'C'中的系列的返回值。 –

回答

4

這裏有一個問題:

pthread_create(sons + sizeof(pthread_t)*i, NULL, sonSimulation, (void *) &indexes[i]); 

您使用

pthread_t *sons = (pthread_t *) malloc(sizeof(pthread_t)*threadNumber); 

所以,sons + sizeof(pthread_t)*ipthread_create是錯誤的分配sons。當您使用sons+i時,由於指針算術的原因,它會自動將sons指針sizeof(pthread_t)字節向前移動。使用sons + sizeof(pthread_t)*i將指針移動到無效內存位置,調用未定義行爲。

要解決此問題,使用

pthread_create(sons + i, NULL, sonSimulation, (void *) &indexes[i]); 

pthread_create(&sons[i], NULL, sonSimulation, (void *) &indexes[i]); 

,而不是

pthread_create(sons + sizeof(pthread_t)*i, NULL, sonSimulation, (void *) &indexes[i]); 

此外,如在評論中指出,在C need not cast the result of malloc(and family)
void*投上最後一個參數是不需要@JoachimPileborgcomments

+0

也不需要在'pthread_create'中投射線程函數參數。 –

+0

我認爲'void *'可以轉換爲任何其他類型而無需投射,但相反需要投射。所以'void *'可以在沒有轉換的情況下進行轉換? –

+0

@CoolGuy:「*所以'void *'可以在沒有強制類型轉換的情況下進行轉換?*」可以轉換爲任何其他類型的指針類型,是的。 – alk