• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

C++中Semaphore内核对象用法实例

c++ 搞代码 4年前 (2022-01-06) 114次浏览 已收录 0个评论

这篇文章主要介绍了C++中Semaphore内核对象用法实例,有助于深入了解信号量(Semaphore)的基本用法,需要的朋友可以参考下

本文实例讲述了C++中Semaphore内核对象的用法,分享给大家供大家参考。具体方法如下:

代码如下:
// Semaphore.cpp : 定义控制台应用程序的入口点。 
// 
 
#include “stdafx.h” 
#include  
#include   
 
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); 
    来源gaodai$ma#com搞$代*码*网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; 
}

希望本文所述对大家的C++程序设计有所帮助。

以上就是C++中Semaphore内核对象用法实例的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:C++中Semaphore内核对象用法实例
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址