进程间互斥访问临界资源
1、使用临界区变量
HANDL g_hMutex;
HANDLE g_hThread[2];
main()
{
g_hMutex=CreateMutex(NULL,FALSE,NULL);
g_hThread[0]=CreateThread(..);
g_hThread[1]=CreateThread(..);
}
LRESULT CALLBACK Thread1Proc(LPVIOD lParam)
{
WaiteForSingleObject(g_hMutex,INIFINTE);
//Read File Operation hear
ReleaseObject(g_hMutex);
}
LRESULT CALLBACK Thread2Proc(LPVIOD lParam)
{
//同上
}
最后要 CloseHandle(g_hMutex);
2、Section Object
CRITICAL_SECTION CS; {声明一个 CriticalSection 结构类型变量; 它应该是全局的}
InitializeCriticalSection(CS); {初始化}
EnterCriticalSection(CS); {开始: 轮到我了其他线程走开}
....(临界资源)
LeaveCriticalSection(CS); {结束: 其他线程可以来了}
DeleteCriticalSection(CS); {删除: 注意不能过早删除}