多线程问题,求高手帮忙看看。
#include <iostream.h>#include <windows.h>
DWORD WINAPI FunPro1(
LPVOID lpParameter // thread data
);
DWORD WINAPI FunPro2(
LPVOID lpParameter // thread data
);
int tickes = 100;
CRITICAL_SECTION g_cs;
void main()
{
HANDLE hThread1 = CreateThread(NULL, 0, FunPro1, NULL, 0, NULL);
HANDLE hThread2 = CreateThread(NULL, 0, FunPro2, NULL, 0, NULL);
CloseHandle(hThread1);
CloseHandle(hThread2);
InitializeCriticalSection(&g_cs);
Sleep(4000);
DeleteCriticalSection(&g_cs);
}
DWORD WINAPI FunPro1(
LPVOID lpParameter // thread data
)
{
while(TRUE)
{
EnterCriticalSection(&g_cs);
if(tickes > 0)
{
Sleep(1);
cout<<"Thread1 sell tickes..."<< tickes--<<endl;
}
else
{
break;
}
LeaveCriticalSection(&g_cs);
}
return 0;
}
DWORD WINAPI FunPro2(
LPVOID lpParameter // thread data
)
{
while(TRUE)
{
EnterCriticalSection(&g_cs);
if(tickes > 0)
{
Sleep(1);
cout<<"Thread2 sell tickes..."<< tickes--<<endl;
}
else
{
break;
}
LeaveCriticalSection(&g_cs);
}
return 0;
}
这个程序用多线程模拟售票系统,但是执行结果只看到一个线程运行,而且有时候会出现错误。代码哪里出了错误??实在找不出什么原因。