天狼鼠

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

*---------------------------------------------------------*\
另一种同步实现
\*---------------------------------------------------------*/
//CRITICAL_SECTION  g_cs;
HANDLE     g_hEvent  = NULL;
HANDLE     g_hMutex  = NULL;
HANDLE     g_hSemaphore = NULL;

static DWORD SynThreadProc1(
        LPVOID lpParameter
        )
{
/*
 EnterCriticalSection(&g_cs);
 AfxMessageBox( _T("SyncThreadProc1") );
 LeaveCriticalSection(&g_cs);
*/
/*
 // 事件对象
 WaitForSingleObject(g_hEvent,INFINITE);
 AfxMessageBox( _T("SyncThreadProc1") );
 SetEvent(g_hEvent);
*/
/*
 // 互斥对象
 WaitForSingleObject(g_hMutex,INFINITE);
 AfxMessageBox( _T("SyncThreadProc1") );
 ReleaseMutex(g_hMutex);
*/
/*
 //  信号量对象
 WaitForSingleObject(g_hSemaphore,INFINITE);
 AfxMessageBox( _T("SyncThreadProc1") );
 ReleaseSemaphore( g_hSemaphore , 1, NULL );
*/
 return 0;
}
static DWORD SynThreadProc2(
        LPVOID lpParameter
        )
{
/*
 EnterCriticalSection(&g_cs);
 AfxMessageBox( _T("SyncThreadProc2") );
 LeaveCriticalSection(&g_cs);
*/
/*
// 事件对象
 WaitForSingleObject(g_hEvent,INFINITE);
 AfxMessageBox( _T("SyncThreadProc2") );
 SetEvent(g_hEvent);
*/
/*
 // 互斥对象
 WaitForSingleObject(g_hMutex,INFINITE);
 AfxMessageBox( _T("SyncThreadProc2") );
 ReleaseMutex(g_hMutex);
*/
/*
 //  信号量对象
 WaitForSingleObject(g_hSemaphore,INFINITE);
 AfxMessageBox( _T("SyncThreadProc1") );
 ReleaseSemaphore( g_hSemaphore , 1, NULL );
*/
 return 0;
}
void CMultiThreadDlg::OnBtnUsageEight()
{
 // TODO: Add your control notification handler code here
 
 HANDLE hThread1 = NULL;
 HANDLE hThread2 = NULL;

 //g_hEvent = CreateEvent(NULL,FALSE,TRUE,NULL);
 //g_hMutex = CreateMutex(NULL,FALSE,NULL);
 g_hSemaphore = CreateSemaphore(NULL,1,1,NULL);

 hThread1 = CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)SynThreadProc1,NULL,0,NULL);
 hThread2 = CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)SynThreadProc2,NULL,0,NULL);

 //使用的时候,你要在适当的时候关闭句柄,不是在这里哦
 //if( g_hEvent )  CloseHandle(g_hEvent);
 //if( g_hMutex )  CloseHandle(g_hMutex);
 //if( g_hSemaphore ) CloseHandle(g_hSemaphore);
 
 if ( hThread1 ) CloseHandle(hThread1);
 if ( hThread2 ) CloseHandle(hThread2);
}

对于临界区要注意对象的初始化和删除:

InitializeCriticalSection(&g_cs);

DeleteCriticalSection(&g_cs);

posted on 2011-03-20 16:53  情有独钟  阅读(226)  评论(0编辑  收藏  举报