MFC多线程出现顺序与自己的变成不符,希望大神赐教
源代码如下,结果应该是从100到0,但是最后结果却显示异常,有重复的还有线程一结果显示一半却接着显示线程二的结果,希望大神能够指点#include<windows.h>#...
源代码如下,结果应该是从100到0,但是最后结果却显示异常,有重复的还有线程一结果显示一半却接着显示线程二的结果,希望大神能够指点
#include<windows.h>
#include<iostream.h>
DWORD WINAPI proc1(LPVOID lpParameter);
DWORD WINAPI proc2(LPVOID lpParameter);
int m_ticket=100;
HANDLE mMuxte;
void main()
{
HANDLE mthread1;
HANDLE mthread2;
mthread1=CreateThread(NULL,0,proc1,NULL,0,NULL);
mthread2=CreateThread(NULL,0,proc2,NULL,0,NULL);
mMuxte=CreateMutex(NULL,FALSE,NULL);
CloseHandle(mthread1);
CloseHandle(mthread2);
Sleep(4000);
}
DWORD WINAPI proc1(LPVOID lpParameter)
{
while(TRUE)
{
WaitForSingleObject(mMuxte,INFINITE);
if(m_ticket>0)
{
Sleep(1);
cout<<"thread1 sell ticket:"<<m_ticket--<<endl;
}
else
break;
ReleaseMutex(mMuxte);
}
return 0;
}
DWORD WINAPI proc2(LPVOID lpParameter)
{
WaitForSingleObject(mMuxte,INFINITE);
while(TRUE)
{
if(m_ticket>0)
{
Sleep(1);
cout<<"thread2 sell ticket:"<<m_ticket--<<endl;
}
else
break;
ReleaseMutex(mMuxte);
}
return 0;
} 展开
#include<windows.h>
#include<iostream.h>
DWORD WINAPI proc1(LPVOID lpParameter);
DWORD WINAPI proc2(LPVOID lpParameter);
int m_ticket=100;
HANDLE mMuxte;
void main()
{
HANDLE mthread1;
HANDLE mthread2;
mthread1=CreateThread(NULL,0,proc1,NULL,0,NULL);
mthread2=CreateThread(NULL,0,proc2,NULL,0,NULL);
mMuxte=CreateMutex(NULL,FALSE,NULL);
CloseHandle(mthread1);
CloseHandle(mthread2);
Sleep(4000);
}
DWORD WINAPI proc1(LPVOID lpParameter)
{
while(TRUE)
{
WaitForSingleObject(mMuxte,INFINITE);
if(m_ticket>0)
{
Sleep(1);
cout<<"thread1 sell ticket:"<<m_ticket--<<endl;
}
else
break;
ReleaseMutex(mMuxte);
}
return 0;
}
DWORD WINAPI proc2(LPVOID lpParameter)
{
WaitForSingleObject(mMuxte,INFINITE);
while(TRUE)
{
if(m_ticket>0)
{
Sleep(1);
cout<<"thread2 sell ticket:"<<m_ticket--<<endl;
}
else
break;
ReleaseMutex(mMuxte);
}
return 0;
} 展开
1个回答
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询