线程互斥问题
#include<windows.h>#include<stdio.h>
int ThreadData=1;
int n;
DWORD f,f1,f2=1;
CRITICAL_SECTION csPrint; // 声明一个临界区
//HANDLE hmutex; //互斥信号量
void Print(char *str)
{
//EnterCriticalSection(&csPrint); // 进入临界区
for (;*str != '\0';str++)
{
Sleep(5000);
printf("%c",*str);
}
printf("\n");
// LeaveCriticalSection(&csPrint); // 退出临界区
}
DWORD WINAPI ThreadProcess(LPVOID lpParameter)
{
//WaitForSingleObject(hmutex,INFINITE);
printf("This is Sub Thread!\n");
for(int i=1;i<=n;i++)
{
f2=f2*i;
printf("f2[%d]=%d\n",i,f2);
}
printf("\n");
ThreadData=0;
//ReleaseMutex(hmutex);
return 0;
}
int main()
{
HANDLE hThread;
DWORD ThreadID;
InitializeCriticalSection(&csPrint); // 初始化临界区
printf("请输入一个小于20的正整数:");
scanf("%d",&n);
// WaitForSingleObject(hmutex,INFINITE); //等待互斥对象
for(int i=1,f1=0;i<=n;i++)
{
f1=f1+i;
printf("f1[%d]=%d\n",i,f1);
}
printf("\n");
// ReleaseMutex(hmutex);
hThread=CreateThread(NULL,0,ThreadProcess,NULL,0,&ThreadID);//创建一个新的线程
while (ThreadData)
{
Print("Main Thread is waiting for Sub Thread!\n");
//Sleep(600);
}
f=f1+f2;
printf("The sum is %d\n",f);
Sleep(1000);
return 0;
}
i是主线程和子线程共同访问的量,为什么主线程和子线程之间没有进行互斥操作 但是它们输出的结果并没有错误呢?求大神们给小弟说一下