首页 > 编程语言 >Semaphore 类 的使用理解C#

Semaphore 类 的使用理解C#

时间:2023-06-05 22:33:59浏览次数:45  
标签:释放 示例 C# 信号量 计数 理解 线程 Semaphore

示例

下面的代码示例创建一个信号量,其最大计数为3,初始计数为零。 该示例启动五个线程,这会阻止等待信号量。 主线程使用 Release(Int32) 方法重载将信号量计数增加到其最大值,从而允许三个线程进入信号量。 每个线程使用 Thread.Sleep 方法等待一秒,以模拟工作,然后调用 Release() 方法重载以释放信号量。 每次释放信号灯时,都将显示以前的信号量计数。 控制台消息跟踪信号量使用。 每个线程的模拟工作时间间隔略有增加,使输出更易于读取。

C# 复制

 

using System;
using System.Threading;

public class Example
{
    // A semaphore that simulates a limited resource pool.
    //
    private static Semaphore _pool;

    // A padding interval to make the output more orderly.
    private static int _padding;

    public static void Main()
    {
        // Create a semaphore that can satisfy up to three
        // concurrent requests. Use an initial count of zero,
        // so that the entire semaphore count is initially
        // owned by the main program thread.
        //
        _pool = new Semaphore(0, 3);

        // Create and start five numbered threads. 
        //
        for(int i = 1; i <= 5; i++)
        {
            Thread t = new Thread(new ParameterizedThreadStart(Worker));

            // Start the thread, passing the number.
            //
            t.Start(i);
        }

        // Wait for half a second, to allow all the
        // threads to start and to block on the semaphore.
        //
        Thread.Sleep(500);

        // The main thread starts out holding the entire
        // semaphore count. Calling Release(3) brings the 
        // semaphore count back to its maximum value, and
        // allows the waiting threads to enter the semaphore,
        // up to three at a time.
        //
        Console.WriteLine("Main thread calls Release(3).");
        _pool.Release(3);

        Console.WriteLine("Main thread exits.");
    }

    private static void Worker(object num)
    {
        // Each worker thread begins by requesting the
        // semaphore.
        Console.WriteLine("Thread {0} begins " +
            "and waits for the semaphore.", num);
        _pool.WaitOne();

        // A padding interval to make the output more orderly.
        int padding = Interlocked.Add(ref _padding, 100);

        Console.WriteLine("Thread {0} enters the semaphore.", num);
        
        // The thread's "work" consists of sleeping for 
        // about a second. Each thread "works" a little 
        // longer, just to make the output more orderly.
        //
        Thread.Sleep(1000 + padding);

        Console.WriteLine("Thread {0} releases the semaphore.", num);
        Console.WriteLine("Thread {0} previous semaphore count: {1}",
            num, _pool.Release());
    }
}

注解

使用 Semaphore 类控制对资源池的访问。 线程通过调用从类继承的方法进入信号量, WaitOne WaitHandle 并通过调用方法释放信号量 Release

每次线程进入信号量时,信号量的计数都将减少,并在线程释放信号量时递增。 如果计数为零,则后续请求会阻塞,直到其他线程释放信号量。 当所有线程都已释放信号量后,计数将达到创建信号量时指定的最大值。

Semaphore 类 的使用理解C#_System

 



标签:释放,示例,C#,信号量,计数,理解,线程,Semaphore
From: https://blog.51cto.com/u_4018548/6420109

相关文章

  • C#中调用c++的dll具体创建与调用步骤,亲测有效~ (待验证)
    使用的工具是VS2010哦~其他工具暂时还没试过我新建的工程名是my21dll,所以会生成2个同名文件。接下来需要改动的只有画横线的部分下面是my21dll.h里面的。。。下面的1是自动生成的不用动,或者也可以不要,因为只是一个宏而已下面可以做相应修改。下面的2是自动生成的类,我没用就注释掉了......
  • 【loj3396】novel(AC自动机维护文本串子串的匹配信息)
    设当前询问的串为\(s_i\)记为\(t\)。考虑\(r\)右移,维护每个\(l\)对应的\(g(l,r)\)和\(\max_{l}\frac{g(l,r)}{r-l+1}\)即可。最基本的观察是:当\(r\)右移后,考虑\(t_{1..r}\)在AC自动机上匹配到的点\(p\),那么对于\(p\)的任意祖先(包含\(p\))\(u\),都会给\(l\leq......
  • DataTemplateSelector介绍
    DataTemplateSelector可以帮助我们实现动态选择数据绑定的模版,如通过ListView+DataTemplateSelector实现微信朋友圈或聊天列表效果。Github已有聊天效果图  喜欢阅读代码请直接移步:https://github.com/nishanil/Xamarin.Forms-Samples/tree/master/DataTemplateSelector本文通过......
  • AMBA2 AHB 相关理解 (一)
    一、AHB总线协议概述1.AHB总线部件主机主机给地址(选通不同slave)以及控制信息(读写方向、数据量、数据大小等)发起读写操作。从机从机在仲裁器给过来的HREADY为高电平时采样HSELx、地址以及控制信号。从机会返回两个信号(HREADYOUT/HRESP)给主机,前者为是否需要主机等待信号......
  • C#中的垃圾回收
     ......
  • C# 线程池ThreadPool的用法简析
    什么是线程池?为什么要用线程池?怎么用线程池?1.什么是线程池?.NETFramework的ThreadPool类提供一个线程池,该线程池可用于执行任务、发送工作项、处理异步I/O、代表其他线程等待以及处理计时器。那么什么是线程池?线程池其实就是一个存放线程对象的“池子(pool)”,他提供了一些基本方......
  • post请求方式 - 抖音生活服务 使用restTemplate而不使用httpClient
    publicstaticStringdoPostForJson(Stringurl,Stringjson,StringbyteAuthorization){RestTemplaterestTemplate=newRestTemplate();logger.info("restTemplateinvokepostmethod.url:[{}],json:[{}]",url,json);long......
  • 【网络基础】用了 TCP 协议,数据一定不会丢吗?
    1  前言TCP是一个可靠的传输协议,那它一定能保证数据不丢失吗?这次,就跟大家探讨这个问题。2  数据包的发送流程首先,我们两个手机的绿皮聊天软件客户端,要通信,中间会通过它们家服务器。大概长这样。但为了简化模型,我们把中间的服务器给省略掉,假设这是个端到端的通信。且为了......
  • net core+mediatr+EF实现事件触发
    参考杨中科的教程1.先添加接口usingMediatR;namespaceNetOptions.Entities;publicinterfaceIDomainEnvent{voidAddNotification(INotificationnotification);IEnumerable<INotification>GetNotifications();voidClearNotifications();}2.添加抽......
  • C++面试八股文:如何在堆上和栈上分配一块内存?
    某日二师兄参加XXX科技公司的C++工程师开发岗位6面:面试官:如何在堆上申请一块内存?二师兄:常用的方法有malloc,new等。面试官:两者有什么区别?二师兄:malloc是向操作系统申请一块内存,这块内存没有经过初始化,通常需要使用memset手动初始化。而new一般伴随三个动作,向操作系统申请一......