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

📄 duelingthreads1.cpp

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

unsigned _stdcall ChildThreadProcedure( LPVOID lpMutex) {
    // covert parameter to mutex handle...
    HANDLE hMutex = (HANDLE) lpMutex;

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

    // repeat three times...
    for (int n =0; n < 3; n++) {
        // wait to acquire the mutex...
        DWORD dwResult = WaitForSingleObject( hMutex, INFINITE);

        if (dwResult == WAIT_OBJECT_0) {
            printf("Thread 0x%08x - acquired the mutex.\n", dwThreadId);
            // hold the mutex for one-half second and sleep...
            Sleep(500);

            printf("Thread 0x%08x - releasing the mutex.\n", dwThreadId);            
            ReleaseMutex(hMutex);

            // wait for one-half second before trying again...
            Sleep(500);
        }
        else {
            printf("Thread 0x%08x - error calling WaitForSingleObject().\n", dwThreadId);
            return 0xFFFFFFFF;
        }
    }

    return 0;
}

int main(void) {
    HANDLE hChildThread[3];
    HANDLE hMutex;

    // create the mutex...
    hMutex = CreateMutex( NULL, FALSE, NULL);
    if (hMutex == NULL) {
        printf("Primary thread - error calling CreateMutex().\n");
        exit(0xFFFFFFFF);
    }

    // create the child threads...
    unsigned uUnusedThreadId;
    hChildThread[0] = (HANDLE)_beginthreadex( NULL, 0, ChildThreadProcedure, (void*) hMutex, 0, &uUnusedThreadId);
    hChildThread[1] = (HANDLE)_beginthreadex( NULL, 0, ChildThreadProcedure, (void*) hMutex, 0, &uUnusedThreadId);
    hChildThread[2] = (HANDLE)_beginthreadex( NULL, 0, ChildThreadProcedure, (void*) hMutex, 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(hMutex);
    CloseHandle(hChildThread[0]);
    CloseHandle(hChildThread[1]);
    CloseHandle(hChildThread[2]);

    return 0;
}

⌨️ 快捷键说明

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