我在學習C線程概念,並且我寫了簡單的下面的代碼。現在,當我編譯並運行它時,會出現意想不到的隨機行爲。帶睡眠C中的線程化
#include <pthread.h>
#include <stdio.h>
void * func_threadName(void * i) {
int *x=(int *)i;
printf("I'm thread : %d\n",*x);
return NULL;
}
main()
{
int iter;
printf("testing multithreading....\n");
pthread_t thread_arr[3];
for (iter=0;iter<3;iter++)
{
pthread_create(&thread_arr[iter],NULL,func_threadName,&iter);
}
for (iter=0;iter<3;iter++)
{
pthread_join(thread_arr[iter],NULL);
}
}
它打印出不可預測的一樣:
[email protected]:~/Documents/my_C_codes$ ./thread_test.o
testing multithreading....
I'm thread : 0
I'm thread : 0
I'm thread : 0
[email protected]:~/Documents/my_C_codes$ ./thread_test.o
testing multithreading....
I'm thread : 0
I'm thread : 2
I'm thread : 1
[email protected]:~/Documents/my_C_codes$ ./thread_test.o
testing multithreading....
I'm thread : 2
I'm thread : 2
I'm thread : 0
但是,當我做出這樣有輕微的變化創建線程後,它完美的作品,並打印順序。
pthread_create(&thread_arr[iter],NULL,func_threadName,&iter);
sleep(1);
現在的輸出是這樣的,每次:
[email protected]:~/Documents/my_C_codes$ ./thread_test.o
testing multithreading....
I'm thread : 0
I'm thread : 1
I'm thread : 2
[email protected]:~/Documents/my_C_codes$ ./thread_test.o
testing multithreading....
I'm thread : 0
I'm thread : 1
I'm thread : 2
[email protected]:~/Documents/my_C_codes$ ./thread_test.o
testing multithreading....
I'm thread : 0
I'm thread : 1
I'm thread : 2
我想了解的是,在第一種情況下,是顯示,因爲所有的線程一個線程之前共享相同的存儲空間,因此不可預知的行爲終止,其他使用相同的值我?歡迎任何其他信息。
-1不,它不是更好,它更糟糕。爲什麼黑客可以簡單地聲明一個數組來保存這些值?壞。 –