#include <windows.h>
int g_share=0;
HANDLE hmutex;
HANDLE g_addEvent;
HANDLE g_decEvent;
DWORD WINAPI AddProc(
LPVOID lpParameter // thread data
);
DWORD WINAPI DecProc(
LPVOID lpParameter // thread data
);
int main()
{
SECURITY_ATTRIBUTES sa;
DWORD dwStackSize=0;
LPVOID lpParameter=NULL;
DWORD dwCreationFlags=0;
DWORD addThreadId;
DWORD decThreadId;
HANDLE addhandle;
HANDLE dechandle;
memset((BYTE *)&sa,0,sizeof(SECURITY_ATTRIBUTES));
sa.nLength=sizeof(SECURITY_ATTRIBUTES);
//创建互斥对象实现g_share的互斥访问
hmutex=CreateMutex(&sa,FALSE,NULL);
//创建事件实现进程同步
g_addEvent=CreateEvent(&sa,FALSE,TRUE,NULL);
g_decEvent=CreateEvent(&sa,FALSE,FALSE,NULL);
addhandle=CreateThread(
&sa,
dwStackSize,
AddProc,
lpParameter,
dwCreationFlags,
&addThreadId);
// Sleep(20);
dechandle=CreateThread(
&sa,
dwStackSize,
DecProc,
lpParameter,
dwCreationFlags,
&decThreadId);
WaitForSingleObject(addhandle,INFINITE);
WaitForSingleObject(dechandle,INFINITE);
CloseHandle(addhandle);
CloseHandle(dechandle);
return 0;
}
DWORD WINAPI AddProc(
LPVOID lpParameter // thread data
)
{
int loop=200;
while(loop>0)
{
WaitForSingleObject(g_addEvent,INFINITE);
loop-=1;
WaitForSingleObject(hmutex,INFINITE);
g_share+=1;
printf("add proc loop: %d g_share:%d\n",loop,g_share);
Sleep(10);
ReleaseMutex(hmutex);
SetEvent(g_decEvent);
}
return 0;
};
DWORD WINAPI DecProc(
LPVOID lpParameter // thread data
)
{
int loop=200;
while(loop>0)
{
WaitForSingleObject(g_decEvent,INFINITE);
loop-=1;
WaitForSingleObject(hmutex,INFINITE);
g_share-=1;
printf("dec proc loop: %d g_share:%d\n",loop,g_share);
Sleep(10);
ReleaseMutex(hmutex);
SetEvent(g_addEvent);
}
return 0;
};
本博客于即日起(2009.2.26)停止更新,