我正在学习 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);
}
}
它无法预测地打印如下:
diwakar@diwakar-VPCEH25EN:~/Documents/my_C_codes$ ./thread_test.o
testing multithreading....
I'm thread : 0
I'm thread : 0
I'm thread : 0
diwakar@diwakar-VPCEH25EN:~/Documents/my_C_codes$ ./thread_test.o
testing multithreading....
I'm thread : 0
I'm thread : 2
I'm thread : 1
diwakar@diwakar-VPCEH25EN:~/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);
现在每次的输出都是这样的:
diwakar@diwakar-VPCEH25EN:~/Documents/my_C_codes$ ./thread_test.o
testing multithreading....
I'm thread : 0
I'm thread : 1
I'm thread : 2
diwakar@diwakar-VPCEH25EN:~/Documents/my_C_codes$ ./thread_test.o
testing multithreading....
I'm thread : 0
I'm thread : 1
I'm thread : 2
diwakar@diwakar-VPCEH25EN:~/Documents/my_C_codes$ ./thread_test.o
testing multithreading....
I'm thread : 0
I'm thread : 1
I'm thread : 2
我想了解在第一种情况下,是否显示了不可预测的行为,因为所有线程共享相同的内存空间,因此在一个线程终止之前,另一个线程使用相同的 i 值?欢迎提供任何其他信息。