当前位置 : 主页 > 手机开发 > harmonyos >

多线程之Semaphore实现线程同步

来源:互联网 收集:自由互联 发布时间:2023-08-25
#include iostream#include process.h#include windows.hlong g_count = 0;long g_sum = 0;static const int g_s_Count = 10;CRITICAL_SECTION g_csThreadParamer;CRITICAL_SECTION g_csThreadCode;HANDLE g_threadEvent;HANDLE g_threadMutex;HANDLE g_threa


#include <iostream>
#include <process.h>
#include <windows.h>

long g_count = 0;
long g_sum   = 0;
static const int g_s_Count = 10;
CRITICAL_SECTION g_csThreadParamer;
CRITICAL_SECTION g_csThreadCode;
HANDLE          g_threadEvent;
HANDLE          g_threadMutex;
HANDLE          g_threadSemaphore;

unsigned int WINAPI ThreadFunc(void *p) {
    int nThreadNum = *(int *)p;

    ReleaseSemaphore(g_threadSemaphore, 1, NULL);

    EnterCriticalSection(&g_csThreadCode);
    g_count++;
    printf("线程编号: %d, 全局资源值为: %d\n", nThreadNum, g_count);
    LeaveCriticalSection(&g_csThreadCode);
    
    return 0;
}

int main(void) {
    std::cout << "Create the Thread" << std::endl;
    g_threadSemaphore = CreateSemaphore(0, 1, 4, NULL);

    InitializeCriticalSection(&g_csThreadCode);

    HANDLE threadHandle[g_s_Count];

    for(int i = 0; i < g_s_Count; ) {
        
        threadHandle[i] = (HANDLE)_beginthreadex(NULL,
                                            0,
                                            ThreadFunc,
                                            &i,
                                            0,
                                            NULL);
       // WaitForSingleObject(g_threadSemaphore, INFINITE); //添加这一句,可以实现多线程同步
        
        ++i;
    }

    WaitForMultipleObjects(g_s_Count, threadHandle, true, INFINITE);

    for(int i = 0; i < g_s_Count; ++i) {
        CloseHandle(threadHandle[i]);
    }
    DeleteCriticalSection(&g_csThreadCode);
    std::cout << "Thread Ending" << std::endl; 

    return 0;
}



网友评论