c++多线程中COUT语句引起的问题
#include<iostream>#include<windows.h>usingnamespacestd;HANDLEhMutex=NULL;DWORDWINAPIF...
#include<iostream>
#include<windows.h>
using namespace std;
HANDLE hMutex=NULL;
DWORD WINAPI Fun(LPVOID lpParameter)
{
for(int i=0;i<10;i++)
{
WaitForSingleObject(hMutex,INFINITE);
cout<<" fun thread display!"<<endl;
Sleep(100);
ReleaseMutex(hMutex);
}
return 0L;
}
void main()
{
HANDLE hThread=CreateThread(NULL,0,Fun,NULL,0,NULL);
hMutex=CreateMutex(NULL,FALSE,"screen");
CloseHandle(hThread);
for(int i=0;i<10;i++)
{
WaitForSingleObject(hMutex,INFINITE);
cout<<"main thread display!"<<endl;
Sleep(100);
ReleaseMutex(hMutex);
}
}
以上一段多线程的小程序,在VC6.0上运行结果如下图所示,为什么第一次FOR 循环时主线程与FUN线程的COUT语句在争抢而以后的9次没有争抢呢?而且我还加了互斥量mutex.请高手赐教,感激涕零! 展开
#include<windows.h>
using namespace std;
HANDLE hMutex=NULL;
DWORD WINAPI Fun(LPVOID lpParameter)
{
for(int i=0;i<10;i++)
{
WaitForSingleObject(hMutex,INFINITE);
cout<<" fun thread display!"<<endl;
Sleep(100);
ReleaseMutex(hMutex);
}
return 0L;
}
void main()
{
HANDLE hThread=CreateThread(NULL,0,Fun,NULL,0,NULL);
hMutex=CreateMutex(NULL,FALSE,"screen");
CloseHandle(hThread);
for(int i=0;i<10;i++)
{
WaitForSingleObject(hMutex,INFINITE);
cout<<"main thread display!"<<endl;
Sleep(100);
ReleaseMutex(hMutex);
}
}
以上一段多线程的小程序,在VC6.0上运行结果如下图所示,为什么第一次FOR 循环时主线程与FUN线程的COUT语句在争抢而以后的9次没有争抢呢?而且我还加了互斥量mutex.请高手赐教,感激涕零! 展开
1个回答
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询