windows系统调用 互斥体mutex

 #include "iostream"
#include "windows.h"
using namespace std; class CCountUpDown{
public:
CCountUpDown(int nAccesses):
m_hThreadInc(INVALID_HANDLE_VALUE),
m_hThreadDec(INVALID_HANDLE_VALUE),
m_hMutexValue(INVALID_HANDLE_VALUE),
m_nValue(),
m_nAccess(nAccesses){
m_hMutexValue=CreateMutex(
NULL,
TRUE,
NULL
);
m_hThreadInc=CreateThread(
NULL,
,
IncThreadProc,
reinterpret_cast<LPVOID>(this),
,
NULL
);
m_hThreadDec=CreateThread(
NULL,
,
DecThreadProc,
reinterpret_cast<LPVOID>(this),
,
NULL
);
ReleaseMutex(m_hMutexValue);
} virtual ~CCountUpDown(){
CloseHandle(m_hThreadInc);
CloseHandle(m_hThreadDec);
CloseHandle(m_hMutexValue);
} virtual void WaitForCompletion(){
if(m_hThreadInc!=INVALID_HANDLE_VALUE&&m_hThreadDec!=INVALID_HANDLE_VALUE){
WaitForSingleObject(m_hThreadInc,INFINITE);
WaitForSingleObject(m_hThreadDec,INFINITE);
}
} protected:
virtual void DoCount(int nStep){
while(m_nAccess>){
WaitForSingleObject(m_hMutexValue,INFINITE); m_nValue+=nStep;
printf("thread:%d valuem,value:%d access:%d\n",GetCurrentThreadId(),m_nValue,m_nAccess);
--m_nAccess;
Sleep(); ReleaseMutex(m_hMutexValue);
}
} static DWORD WINAPI IncThreadProc(LPVOID lpParam){
CCountUpDown *pThis=reinterpret_cast<CCountUpDown*>(lpParam);
pThis->DoCount(+);
return ();
} static DWORD WINAPI DecThreadProc(LPVOID lpParam){
CCountUpDown*pThis=reinterpret_cast<CCountUpDown*>(lpParam);
pThis->DoCount(-);
return();
} protected:
HANDLE m_hThreadInc;
HANDLE m_hThreadDec;
HANDLE m_hMutexValue;
int m_nValue;
int m_nAccess;
}; void main(){
CCountUpDown ud();
ud.WaitForCompletion();
getchar();
}
上一篇:vue-cli 引入 Element-UI


下一篇:objective-c中自己创建的对象为什么不能调用release