模拟售票程序。


未加锁程序:


#include <iostream.h>
#include <windows.h>

int index = 0;
int ti = 100;

DWORD WINAPI fun1(
LPVOID lpParameter
);
DWORD WINAPI fun2(
LPVOID lpParameter
);
void main()
{
HANDLE hthread1;
hthread1 = CreateThread(NULL,0,fun1,NULL,0,NULL);
CloseHandle(hthread1);
HANDLE hthread2;
hthread2 = CreateThread(NULL,0,fun2,NULL,0,NULL);
CloseHandle(hthread2);

Sleep(4000);//这样主线程不占用CPU

}

DWORD WINAPI fun1(
LPVOID lpParameter
)
{
while(true)
{

if (ti>0)
{

ti--;
cout<<"thread 11111:"<<ti<<endl;

}
else
break;


}

return 0;
}
DWORD WINAPI fun2(
LPVOID lpParameter
)
{
while(true)
{

if (ti>0)
{

ti--;
cout<<"thread 22222:"<<ti<<endl;
Sleep(5);

}
else
break;


}
return 0;
}


加锁程序:


#include <iostream.h>
#include <windows.h>

int index = 0;
int ti = 100;
HANDLE hmutex;//锁
DWORD WINAPI fun1(
LPVOID lpParameter
);
DWORD WINAPI fun2(
LPVOID lpParameter
);
void main()
{
HANDLE hthread1;
hthread1 = CreateThread(NULL,0,fun1,NULL,0,NULL);
CloseHandle(hthread1);
HANDLE hthread2;
hthread2 = CreateThread(NULL,0,fun2,NULL,0,NULL);
CloseHandle(hthread2);
hmutex = CreateMutex(NULL,TRUE,NULL);
// WaitForSingleObject(hmutex,INFINITE);
ReleaseMutex(hmutex);
Sleep(4000);//这样主线程不占用CPU

}

DWORD WINAPI fun1(
LPVOID lpParameter
)
{
while(true)
{
WaitForSingleObject(hmutex,INFINITE);
if (ti>0)
{

ti--;
cout<<"thread 11111:"<<ti<<endl;

}
else
break;
ReleaseMutex(hmutex);

}

return 0;
}
DWORD WINAPI fun2(
LPVOID lpParameter
)
{
while(true)
{
WaitForSingleObject(hmutex,INFINITE);
if (ti>0)
{

ti--;
cout<<"thread 22222:"<<ti<<endl;
Sleep(5);

}
else
break;
ReleaseMutex(hmutex);

}
return 0;
}


可以根据运行结果比较区别,未加锁程序显然存在BUG,多次售同一张票。