看流星社区

 找回密码
 注册账号
查看: 2776|回复: 0

Semaphore内核对象的使用

[复制链接]

该用户从未签到

发表于 2017-6-2 13:28:48 | 显示全部楼层 |阅读模式
Semaphore内核对象的使用
// Semaphore.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <Windows.h>
#include <process.h>

HANDLE g_hSemaphore;
DWORD g_nConut1 = 0;
DWORD g_nConut2 = 0;
unsigned __stdcall ThreadProc1( void* pArguments )
{
        ::WaitForSingleObject(g_hSemaphore, INFINITE);
        for (int i=0;i<10000;i++)
        {
                g_nConut1++;
                g_nConut2++;
        }
        ::ReleaseSemaphore(g_hSemaphore, 1, NULL);
        printf("ThreadProc1\n");
        return 0;
}

unsigned __stdcall ThreadProc2( void* pArguments )
{
        ::WaitForSingleObject(g_hSemaphore, INFINITE);
        for (int i=0;i<10000;i++)
        {
                g_nConut1++;
                g_nConut2++;
        }
        ::ReleaseSemaphore(g_hSemaphore, 1, NULL);
        printf("ThreadProc2\n");
        return 0;
}

unsigned __stdcall ThreadProc3( void* pArguments )
{
        ::WaitForSingleObject(g_hSemaphore, INFINITE);
        for (int i=0;i<10000;i++)
        {
                g_nConut1++;
                g_nConut2++;
        }
        ::ReleaseSemaphore(g_hSemaphore, 1, NULL);
        printf("ThreadProc3\n");
        return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
        g_hSemaphore = ::CreateSemaphore(NULL, 2, 2, NULL);
        HANDLE hThread[3];
        hThread[0] = (HANDLE)::_beginthreadex(NULL, 0, ThreadProc1, NULL, 0, NULL);
        hThread[1] = (HANDLE)::_beginthreadex(NULL, 0, ThreadProc2, NULL, 0, NULL);
        hThread[2] = (HANDLE)::_beginthreadex(NULL, 0, ThreadProc3, NULL, 0, NULL);

        ::WaitForMultipleObjects(2,hThread,TRUE, INFINITE);
        printf("g_count1=%d\n", g_nConut1);
        printf("g_count2=%d\n", g_nConut2);
        printf("main finished.\n");
        return 0;
}
点击按钮快速添加回复内容: 支持 高兴 激动 给力 加油 苦寻 生气 回帖 路过 感恩
您需要登录后才可以回帖 登录 | 注册账号

本版积分规则

小黑屋|手机版|Archiver|看流星社区 |网站地图

GMT+8, 2024-3-19 11:27

Powered by Kanliuxing X3.4

© 2010-2019 kanliuxing.com

快速回复 返回顶部 返回列表