多线程专题之线程同步(2)
发布日期:2022-04-11 08:52:43 浏览次数:3 分类:博客文章

本文共 2089 字,大约阅读时间需要 6 分钟。

*---------------------------------------------------------*\

另一种同步实现
\*---------------------------------------------------------*/
//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);

转载地址:https://www.cnblogs.com/tianlangshu/archive/2011/03/20/1989564.html 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:多线程专题之线程间的通信
下一篇:多线程专题之线程同步(1)

发表评论

最新留言

第一次来,支持一个
[***.219.124.196]2024年04月15日 15时30分00秒