我有一個基於傳遞給進程的參數創建多個線程的進程。動態創建線程並傳遞一個整數
producer_threads[num_threads];
for (id = 0; id < num_threads; id++)
{
printf("%d\n", id);
pthread_create(&producer_threads[id], NULL, &produce, (void *) &id);
}
每個線程進入一個產生函數並存儲該ID作爲然而我接收的輸出如圖
0
1
Thread <n> started to produce
Thread <n> started to produce
和n是隨機地要麼0的局部變量
void* produce (void* args)
{
int my_id = * (int*) args;
printf("Thread %d started to produce\n", my_id);
}
,1或2.我不確定是什麼導致了問題,除非是因爲全局變量在被本地分配之前正在更新。或者因爲「局部變量」在線程之間共享。