c++多线程中主线程运行机制
#include<Windows.h>#include<iostream>usingnamespacestd;DWORDWINAPIFun1Proc(LPVOIDIpPa...
#include <Windows.h>
#include <iostream>
using namespace std;
DWORD WINAPI Fun1Proc(LPVOID IpParameter);
DWORD WINAPI Fun2Proc(LPVOID IpParameter);
HANDLE hMutex;
void main()
{
HANDLE hThread1;
HANDLE hThread2;
hMutex = CreateMutex(NULL, FALSE, NULL);
hThread1 = CreateThread(NULL,0,Fun1Proc,NULL,0,NULL);
hThread2 = CreateThread(NULL,0,Fun2Proc,NULL,0,NULL);
CloseHandle(hThread1);
CloseHandle(hThread2);
cout<<"main:running"<<endl;
Sleep(4000);
}
DWORD WINAPI Fun1Proc(LPVOID IpParameter)
{
WaitForSingleObject(hMutex,INFINITE);
cout<<"fun1:a"<<endl;
ReleaseMutex(hMutex);
return 0;
}
DWORD WINAPI Fun2Proc(LPVOID IpParameter)
{
WaitForSingleObject(hMutex,INFINITE);
cout<<"fun2:b"<<endl;
ReleaseMutex(hMutex);
return 0;
}
为何主线程有时会输出两次?主线程的运行机制是怎样的? 展开
#include <iostream>
using namespace std;
DWORD WINAPI Fun1Proc(LPVOID IpParameter);
DWORD WINAPI Fun2Proc(LPVOID IpParameter);
HANDLE hMutex;
void main()
{
HANDLE hThread1;
HANDLE hThread2;
hMutex = CreateMutex(NULL, FALSE, NULL);
hThread1 = CreateThread(NULL,0,Fun1Proc,NULL,0,NULL);
hThread2 = CreateThread(NULL,0,Fun2Proc,NULL,0,NULL);
CloseHandle(hThread1);
CloseHandle(hThread2);
cout<<"main:running"<<endl;
Sleep(4000);
}
DWORD WINAPI Fun1Proc(LPVOID IpParameter)
{
WaitForSingleObject(hMutex,INFINITE);
cout<<"fun1:a"<<endl;
ReleaseMutex(hMutex);
return 0;
}
DWORD WINAPI Fun2Proc(LPVOID IpParameter)
{
WaitForSingleObject(hMutex,INFINITE);
cout<<"fun2:b"<<endl;
ReleaseMutex(hMutex);
return 0;
}
为何主线程有时会输出两次?主线程的运行机制是怎样的? 展开
1个回答
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询