zoukankan      html  css  js  c++  java
  • 线程同步-使用SimaphoreSlim类

    SimaphoreSlim类是作为Semaphore类的轻量级版本的。该类限制了同时访问同一个资源的线程数量。

    代码Demo:

    using System;
    using System.Threading;

    在Main方法下面加入以下代码片段:

     static SemaphoreSlim _semaphore = new SemaphoreSlim(4);------1

    static void AccessDatabase(string name, int seconds)
    {
    Console.WriteLine("{0} waits to access a database", name);
    _semaphore.Wait();
    Console.WriteLine("{0} was granted an access to a database", name);
    Thread.Sleep(TimeSpan.FromSeconds(seconds));
    Console.WriteLine("{0} is completed", name);
    _semaphore.Release();
    }

    在Main方法中加入以下代码片段:

    for (int i = 1; i <= 6; i++)
    {
     string threadName = "Thread" + i;
     int secondsToWait = 2 + 2 * i;
     var t = new Thread(() => AccessDatabase(threadName, secondsToWait));
     t.Start();
    }

    工作原理:

    主线程启动时,创建了SemaphoreSlim的一个实例,并在其构造函数中制定允许的并发线程数量(1行所示)。然后启动了6个不同名称和不同初始运动时间的线程。

    每个线程都尝试获取数据库的访问,但是我们借助于信号系统限制了访问数据库的并发数为4个线程。当有4个线程获取了数据库的访问后,其它两个线程需要等待,知道之前线程中的某一个完成工作并调用_semaphore.Release方法来发出信号。

  • 相关阅读:
    去除vue-router 链接上的#号
    input 实现调用本地摄像头 实现拍照 和拍视频
    vue-cli 安装sass 和 font-awesome 笔记
    linux下alias命令详解
    linux下source命令的基本功能
    在Linux命令行窗口中,怎么向上翻页?
    Android内存监测工具使用
    Activity的Theme主题风格
    ListView中CheckBox错乱解决
    绘图之Canvas学习
  • 原文地址:https://www.cnblogs.com/v-haoz/p/9260521.html
Copyright © 2011-2022 走看看