xian3

C#多线程:使用Semaphore类限制资源并发访问数

考虑这样的一个场景:一个停车场的只含一定数量的停车位,只有当停车场中还有空位时,停车场的入口才会打开。C#提供了Semaphore类来处理这种场景。Semaphore类可以在构造时指定资源数量,使用WaitOne方法等待一个资源,使用Release方法释放一个资源。示例代码:

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

using System.Threading;

namespace ProcessTest
{
    class Program
    {
        static Semaphore semaphore;

        static void Main(string[] args)
        {
            //创建一个限制资源类
            //资源数为5,开放资源数为2
            //主线程自动占有3个资源
            semaphore = new Semaphore(2, 5);

            //开启3个线程,让它们竞争剩余的2个资源
            for (int i = 0; i < 3; i++)
            {
                Thread t = new Thread(new ThreadStart(WorkerProc));
                t.Name = "Thread" + i;
                t.Start();
                Thread.Sleep(30);
            }

            System.Console.ReadKey();
        }

        static void WorkerProc()
        {
            for (int i = 0; i < 3; i++)
            {
                //等一个资源信号
                semaphore.WaitOne();
                Console.WriteLine(Thread.CurrentThread.Name + ": Begin");
                Thread.Sleep(200);
                Console.WriteLine(Thread.CurrentThread.Name + ": End");
                //释放资源
                semaphore.Release();
            }
        }
    }
}

C#多线程:Interlocked类操作

 System.Threading.Interlocked类为多个线程共享的变量提供原子操作。

为整型类提供原子类操作

  经验显示,那些需要在多线程情况下被保护的资源通常是整型值,且这些整型值在多线程下最常见的操作就是递增、递减或相加操作。Interlocked类提供了一个专门的机制用于完成这些特定的操作。这个类提供了Increment、Decrement、Add静态方法用于对int或long型变量的递增、递减或相加操作。

  示例代码:

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

using System.Threading;

namespace ProcessTest
{
    class Program
    {
        static int counter = 0;

        static void Main(string[] args)
        {
            Thread t1 = new Thread(new ThreadStart(F1));
            Thread t2 = new Thread(new ThreadStart(F2));

            t1.Start();
            t2.Start();

            t1.Join();
            t2.Join();

            System.Console.ReadKey();
        }

        static void F1()
        {
            for (int i = 0; i < 5; i++)
            {
                Interlocked.Increment(ref counter);
                System.Console.WriteLine("Counter++ {0}", counter);
                Thread.Sleep(10);
            }
        }

        static void F2()
        {
            for (int i = 0; i < 5; i++)
            {
                Interlocked.Decrement(ref counter);
                System.Console.WriteLine("Counter-- {0}", counter);
                Thread.Sleep(10);
            }
        }
    }
}

  

原文地址:https://www.cnblogs.com/jiaoluo/p/3548781.html