请教高手一个多线程编程的问题
#include<windows.h>#include<iostream.h>
DWORD WINAPI Fun1Proc(LPVOID lpParameter);
DWORD WINAPI Fun2Proc(LPVOID lpParameter);
int i=0;
int ticket=100;
void main()
{
HANDLE hThread1;
HANDLE hThread2;
hThread1=CreateThread(NULL,0,Fun1Proc,NULL,0,NULL);
hThread2=CreateThread(NULL,0,Fun2Proc,NULL,0,NULL);
CloseHandle(hThread1);
CloseHandle(hThread2);
while(i++<10000)
{
cout<<"main is running"<<endl;
}
}
DWORD WINAPI Fun1Proc(LPVOID lpParameter)
{
while(i++<10000)
{
while(1)
{
if(ticket>0)
cout<<"thread1 sell ticket: "<<ticket--<<endl;
else
break;
}}
return 0;
}
DWORD WINAPI Fun2Proc(LPVOID lpParameter)
{
while(1)
{
if(ticket>0)
cout<<"thread2 sell ticket: "<<ticket--<<endl;
else
break;
}
return 0;
}这个程序中,不采用Sleep()函数而采用while循环来使主函数不会那么早结束,但为什么主函数中改成//cout<<"main is running"<<endl;,注释起来,则线程1,2都不会执行了?
若不注释,将线程1中去掉任何一个循环,为什么也会导致线程1,2不能执行?