#include<stdio.h>
#include<stdlib.h>
#include<windows.h>
int accnt1 = 0;
int accnt2 = 0;
double begin=0,end=0,time=0;
int i = 1;
HANDLE hMutex;
DWORD WINAPI run(LPVOID p){
int counter = 0;
int temp1,temp2,r;
begin=GetTickCount();
do{
WaitForSingleObject(hMutex,INFINITE);
// printf("%d\n",GetCurrentThreadId());
temp1 = accnt1;
temp2 = accnt2;
r = rand();
accnt1 = temp1+r;
accnt2 = temp2-r;
ReleaseMutex(hMutex);
counter++;
}while(accnt1+accnt2==0&&counter<10000000);
end =GetTickCount();
time = end - begin;
printf("Thread %d counter is %d \n time is %.4f \n",i,counter,time);
i++;
return 0;
}
int main(){
hMutex = CreateMutex(NULL,FALSE,NULL);
CreateThread(NULL,0,run,NULL,0,NULL);
CreateThread(NULL,0,run,NULL,0,NULL);
system("PAUSE");
return 0;
}
加了锁为什么第一个线程还是无法完成啊