请问为什么运行下列程序后,gCount的值不为5,而是为一个莫名其妙的随机数啊?
如果说是多线程影响的,那毕竟加和减在两个函数里都限定死了为10000000次,那运算结果应该还是为5啊?
整个运行机制到底是怎样的?
求大神解答!
#include
#include
#include
volatile unsigned int gCount=5;
//gCount是全局共享变量,volatile表明不进行优化
unsigned __stdcall FirstThreadFunc(void *pArguments)
{
int i;
for(i=0;i<10000000;i++)
{
gCount=gCount+1;
}
return 0;
}
unsigned __stdcall SecondThreadFunc(void *pArguments)
{
int i;
for(i=0;i<10000000;i++)
{
gCount=gCount-1;
}
return 0;
}
int main()
{
HANDLE hThread[2];
unsigned threadID[2];
printf("gCount的初始值为%d\n",gCount);
hThread[0]=(HANDLE)_beginthreadex(NULL,0,FirstThreadFunc,NULL,0,&threadID[0]);
hThread[1]=(HANDLE)_beginthreadex(NULL,0,SecondThreadFunc,NULL,0,&threadID[1]);
WaitForSingleObject(hThread[0],INFINITE);
WaitForSingleObject(hThread[1],INFINITE);
CloseHandle(hThread[0]);
CloseHandle(hThread[1]);
printf("并发修改后,gCount的值为%d\n",gCount);
return 0;
}