c#-线程同步-semaphore(信号量)-简单实验

1.概述

1.1.使用场景:比如io的访问控制,只有3个端口,当有第4个需要连接的时候,就需要等待,直到有一个io端口释放。

1.2.特点:与互斥类似,只不过信号量可以由多个线程同时使用,比如设置的信号数是2,那就两个线程可以使用,但第3个线程需等待。

2.代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Diagnostics;

namespace ConsoleApp6
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("hello word");
            int threadCount = 6;
            //semaphore
            // n.信号标,旗语;臂板信号装置; v.打旗语,发信号
            int semaphoreCount = 4;
            var semaphore = new SemaphoreSlim(semaphoreCount, semaphoreCount);
            var thread = new Thread[threadCount];
            for (int i = 0; i < threadCount; i++) {
                thread[i] = new Thread(ThreadMain);
                thread[i].Start(semaphore);
            }
            for (int i=0; i< threadCount; i++) {
                thread[i].Join();  
            }
            Console.WriteLine("All thread finished");
            Console.ReadKey();
        }
        static void ThreadMain(object o) {
            SemaphoreSlim semaphore = o as SemaphoreSlim;
            Trace.Assert(semaphore != null, "o must be a SemaphoreSlim type");
            bool isCompleted = false;
            while (!isCompleted) {
                if (semaphore.Wait(600))
                {
                    try
                    {
                        Console.WriteLine("Thread {0} locks the semaphore", Thread.CurrentThread.ManagedThreadId);
                        Thread.Sleep(2000);
                    }
                    finally
                    {
                        semaphore.Release();
                        Console.WriteLine("Thread {0} releases the semphore", Thread.CurrentThread.ManagedThreadId);
                        isCompleted = true;
                    }
                }
                else {
                    Console.WriteLine("Timeout for thread {0} ", Thread.CurrentThread.ManagedThreadId);
                }
            }
        }
    }
}

3 运行效果

4.代码分析

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值