`
wyf
  • 浏览: 432949 次
  • 性别: Icon_minigender_1
  • 来自: 唐山
社区版块
存档分类
最新评论

Semaphore,SemaphoreSlim用法

    博客分类:
  • C#
阅读更多

1、限制可同时访问某一资源或资源池的线程数。

 SemaphoreSlim为Semaphore 的轻量替代

使用:实例化一个初始值0最大值3

private static Semaphore _pool;
 _pool = new Semaphore(0, 3);

 _pool.Release(3);

释放三个线程访问

如下代码:

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. 
        //创建5个线程,先允许三个访问
        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());
    }
}

 

using System;
using System.Threading;
using System.Threading.Tasks;

public class Example
{
    private static SemaphoreSlim semaphore;
    // A padding interval to make the output more orderly.
    private static int padding;

    public static void Main()
    {
        // Create the semaphore.
        semaphore = new SemaphoreSlim(0, 3);
        Console.WriteLine("{0} tasks can enter the semaphore.",
                          semaphore.CurrentCount);
        Task[] tasks = new Task[5];
        
        // Create and start five numbered tasks.
        for(int i = 0; i <= 4; i++)
        {
            tasks[i] = Task.Run( () => {
            // Each task begins by requesting the semaphore.
            Console.WriteLine("Task {0} begins and waits for the semaphore.",
                              Task.CurrentId);
            semaphore.Wait();

            Interlocked.Add(ref padding, 100);

            Console.WriteLine("Task {0} enters the semaphore.", Task.CurrentId);

            // The task just sleeps for 1+ seconds.
            Thread.Sleep(1000 + padding);

            Console.WriteLine("Task {0} releases the semaphore; previous count: {1}.",
                              Task.CurrentId, semaphore.Release()); } );
        }

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

        // Restore the semaphore count to its maximum value.
        Console.Write("Main thread calls Release(3) --> ");
        semaphore.Release(3);
        Console.WriteLine("{0} tasks can enter the semaphore.",
                          semaphore.CurrentCount);
        // Main thread waits for the tasks to complete.
        Task.WaitAll(tasks);
        
        Console.WriteLine("Main thread exits.");
    }
}
// The example displays output like the following:
//       0 tasks can enter the semaphore.
//       Task 1 begins and waits for the semaphore.
//       Task 5 begins and waits for the semaphore.
//       Task 2 begins and waits for the semaphore.
//       Task 4 begins and waits for the semaphore.
//       Task 3 begins and waits for the semaphore.
//       Main thread calls Release(3) --> 3 tasks can enter the semaphore.
//       Task 4 enters the semaphore.
//       Task 1 enters the semaphore.
//       Task 3 enters the semaphore.
//       Task 4 releases the semaphore; previous count: 0.
//       Task 2 enters the semaphore.
//       Task 1 releases the semaphore; previous count: 0.
//       Task 3 releases the semaphore; previous count: 0.
//       Task 5 enters the semaphore.
//       Task 2 releases the semaphore; previous count: 1.
//       Task 5 releases the semaphore; previous count: 2.
//       Main thread exits.

 

分享到:
评论

相关推荐

    SemaphoreSlim,SemaphoreSlim

    static SemaphoreSlim semaphore = new SemaphoreSlim(3); // 初始化为3个并发任务 static async Task Worker(int taskId) { await semaphore.WaitAsync(); // 请求资源 try { Console.WriteLine($"Task {...

    semaphore-scheduling:SemaphoreSlim的实现可用于计划项目中的任务许可(它提供了功能来处理线程或任务是否可以继续其处理或执行次数受到限制?)

    在实际项目中,开发者可以根据具体需求调整SemaphoreSlim的初始化值,以及如何在任务中使用WaitAsync和Release方法,以达到最佳的性能和资源利用率。通过深入理解和灵活运用SemaphoreSlim,我们可以构建出更加健壮、...

    C#的多线程同步,C#中四种进程或线程同步互斥的控制方法

    `Semaphore`可以用于跨进程同步,而`SemaphoreSlim`仅限于在同一应用程序域内的线程之间使用。 下面是一个使用`SemaphoreSlim`的示例: ```csharp using System.Threading; public class SemaphoreExample { ...

    归纳一下C#线程同步的几种方法.docx

    你可以使用`Monitor.Enter`和`Monitor.Exit`方法来锁定和解锁对象,或者使用`Monitor.TryEnter`尝试进入临界区,这在需要检查是否可以进入临界区时很有用。 5. **Mutex、Semaphore 和 SemaphoreSlim**: 这些都是...

    C# VS2013 收串口数据 线程安全

    如果你知道最多只有N个线程可以安全地访问串口,可以使用`Semaphore`或`SemaphoreSlim`。 5. **异步编程(Async/Await)**:使用异步编程模型,如`async/await`关键字,可以避免阻塞线程,提高程序响应性。但是,...

    C#读写线程同步Demo

    3. **Semaphore和SemaphoreSlim**:Semaphore用于控制同时访问特定资源的线程数量。在读写操作中,我们可以设置一个大于1的信号量值,允许多个读线程并发,但限制写线程为1。 4. **ReaderWriterLock和...

    Visual Basic.NET线程参考手册

    这本书深入探讨了线程的概念、使用方法以及在VB.NET中的最佳实践。 首先,线程是操作系统分配CPU时间的基本单位,允许应用程序同时执行多个独立的任务。在VB.NET中,可以使用`System.Threading`命名空间中的类来...

    duoxiancheng.zip_C# duoxiancheng_多线程 界面

    为了确保线程安全,C#提供了多种机制,如Monitor类(用于实现锁)、Mutex、Semaphore和SemaphoreSlim等同步结构,以及lock关键字,它们可以帮助开发者控制对共享资源的访问。 此外,`System.Threading.Tasks`命名...

    C#多线程详细解答.pdf

    3. Mutex、Semaphore和SemaphoreSlim:用于限制同时访问资源的线程数量,实现线程同步。 四、线程间通信 1. WaitHandle集合:包括Mutex、Semaphore、EventWaitHandle等,通过WaitOne、SignalOne等方法实现线程间的...

    C# 多线程编程

    C#提供了多种同步机制,如 Monitor(互斥锁)、Mutex、Semaphore 和 SemaphoreSlim、EventWaitHandle 以及 ReaderWriterLockSlim。Monitor 使用 `.Enter()` 和 `.Exit()` 方法来控制对共享资源的访问;Mutex 和 ...

    Concurrency in C# Cookbook (原版)

    5. **并发控制**:讲解了Mutex、Semaphore、SemaphoreSlim和Monitor等同步原语,以及如何使用它们来控制对共享资源的访问,防止数据竞争。 6. **并行数据处理**:介绍了Parallel LINQ (PLINQ) 和Parallel.ForEach,...

    C#多线程整合事例程序

    4. **Semaphore 和 SemaphoreSlim 类**:这些类用于线程同步,限制同时访问特定资源的线程数量,防止资源竞争过度。 5. **Mutex 和 Monitor 类**:这两个类也是线程同步工具,用于保护共享资源免受并发访问。Mutex...

    C#.NET多线程实例6个(包括多线程基本使用,多线程互斥等全部多线程使用实例).rar.rar

    - **Semaphore 和 SemaphoreSlim**:限制同时访问资源的线程数量。 3. **线程池** .NET Framework 提供了线程池,可以有效管理线程,提高系统效率。使用`ThreadPool.QueueUserWorkItem`方法将工作项添加到线程池...

    c#多线程,利用互斥对象管理,代码简单加注释

    除了Mutex,C#还提供了其他同步机制,如Monitor、Semaphore、SemaphoreSlim、ReaderWriterLockSlim等,它们在不同的场景下各有优势。例如,Monitor适用于简单的同步需求,Semaphore用于控制对有限资源的访问数量,而...

    C#线程参考手册 线程学习

    3. Semaphore和SemaphoreSlim:用于限制同时访问特定资源的线程数量。 四、线程状态与控制 1. 线程状态:新建、可运行、运行、等待、停止等。可以使用Thread.CurrentThread.IsAlive、Thread.Sleep、Thread.Abort等...

    Demo_Threads.zip

    4. 使用Semaphore和SemaphoreSlim:控制对有限资源的并发访问数量。 五、异步编程与Task类 虽然多线程可以实现并行处理,但VB.NET的异步编程模型(如Task类)提供了另一种方式来提高程序的响应性,尤其在I/O密集型...

    C#.NET多线程实例6个(包括多线程基本使用,多线程互斥等全部多线程使用实例)__0525).rar

    - **Semaphore和SemaphoreSlim**:用于限制同时访问特定资源的线程数量,类似“信号量”概念。 - **Lock语句**:C#的`lock`关键字基于 Monitor 对象实现,确保同一时间只有一个线程执行特定代码块。 4. **线程池*...

    C# 多线程管理及运用

    除了使用事件进行线程同步,C#还提供了其他同步机制,如锁(`lock`关键字)、 Monitor、Mutex、Semaphore 和 SemaphoreSlim 等。这些同步原语可以防止数据竞争,确保并发访问的数据一致性。例如,可以使用`lock`...

    dotNetFramework多线程编程

    本文将深入探讨.NET Framework中多线程的概念、使用方法以及最佳实践。 一、多线程基础 在计算机系统中,线程是执行单元,它在进程的上下文中运行,共享进程的资源,如内存、打开的文件等。多线程允许应用程序同时...

    Threading.pdf

    文档可能涵盖了EventWaitHandle、CountdownEvent、Mutex、Semaphore和SemaphoreSlim以及Barrier等同步原语的使用。 9. **SpinLock和SpinWait(自旋锁和自旋等待)**: 在竞争条件下的同步问题中,SpinLock和...

Global site tag (gtag.js) - Google Analytics