⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 cduelingcritsec.cpp

📁 window下的多线程编程参考书。值得一读
💻 CPP
字号:
#include <stdio.h>
#include "CMcl.h"

unsigned _stdcall ChildThreadProcedure( LPVOID lpcCritSec) {
    // convert parameter to the critical section object pointer...
    CMclCritSec *pCritSec = (CMclCritSec *)lpcCritSec;

    // save this thread's id...
    DWORD dwThreadId = GetCurrentThreadId();

    // repeat three times...
    for (int n =0; n < 3; n++) {
        // wait to acquire the critical section...
        pCritSec->Enter();
        printf("Thread 0x%08x - acquired the critical section.\n", dwThreadId);

        // hold the critical section for one-half second and sleep...
        Sleep(500);

        // release the critical section...
        printf("Thread 0x%08x - releasing the critical section.\n", dwThreadId);            
        pCritSec->Leave();

        // wait for one-half second before trying again...
        Sleep(500);
    }

    return 0;
}

int main(void) {
    // create the critical section object...
    CMclCritSec cCritSec;

    // create the child threads, passing a pointer to the 
    // critical section object...
    HANDLE hChildThread[3];
    unsigned uUnusedThreadId;
    hChildThread[0] = (HANDLE)_beginthreadex( NULL, 0, ChildThreadProcedure, (void*) &cCritSec, 0, &uUnusedThreadId);
    hChildThread[1] = (HANDLE)_beginthreadex( NULL, 0, ChildThreadProcedure, (void*) &cCritSec, 0, &uUnusedThreadId);
    hChildThread[2] = (HANDLE)_beginthreadex( NULL, 0, ChildThreadProcedure, (void*) &cCritSec, 0, &uUnusedThreadId);
    if (!hChildThread[0] || !hChildThread[1] || !hChildThread[2]) {
        printf("Primary thread - error creating child threads.\n");
        exit(0xFFFFFFFF);
    }

    // wait until the child threads have exited...
    DWORD dwResult = WaitForMultipleObjects( 3, hChildThread, TRUE, INFINITE);
    if (dwResult != WAIT_OBJECT_0) {
        printf("Primary thread - error calling WaitForMultipleObjects().\n");
        exit(0xFFFFFFFF);
    }

    // clean up all handles...
    CloseHandle(hChildThread[0]);
    CloseHandle(hChildThread[1]);
    CloseHandle(hChildThread[2]);

    // the critical section is cleaned up automatically by 
    // the ~CMclCritSec destructor...
    return 0;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -