zoukankan      html  css  js  c++  java
  • 多线程专题之线程同步(2)

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

  • 相关阅读:
    中国广电工信战争
    围观一个People Search
    Popular榜单能做到小众化吗?
    校园招聘:内地大学生的视野和实践有问题吗?
    锐推榜的平衡策略
    PyQt 自定义信号带参数 emit
    Python pyinstaller
    Python 匿名函数 lambda
    PyQT5 绑定函数的传参(connect 带参数)
    Excel 一列文本变为数字
  • 原文地址:https://www.cnblogs.com/tianlangshu/p/1989564.html
Copyright © 2011-2022 走看看