C#的多线程能力(Mutex的作用)

System.Threading.Mutex :同步基元,它只向一个线程授予对共享资源的独占访问权。当有两个或两个以上的线程要对一个共享资源进行操作的时候,就要

System.Threading.Mutex 互斥体来进行调节。保证只有一个线程可以对共享资源进行控制。如果一个线程获得了互斥体,其他线程只能在第一个线程放弃互斥体之前先挂起。互斥体可以通过waitone() 请求相同的互斥体而不会阻塞其执行

但必须在使用后 ReleaseMutex 来释放互斥体。

下边是示例代码

using System;

using System.Collections.Generic;

using System.Text;

using System.Threading;

using System.Collections;

namespace ConsoleApplication19

{

    

     class Program

     {

         public static ArrayList student = new ArrayList ();

         public static bool flag = false ;

         static void Main(string [] args)

         {

              Thread schooladd = new Thread (students .Add);

              schooladd.Start();

              Thread schoolreduce = new Thread (students .Reduce);

              schoolreduce.Start();

              string d = Console .ReadLine();

}

     }

     class students

     {

         public static System.Threading.Mutex mutex = new System.Threading.Mutex (false ,null /*"Program.student"*/ , out Program .flag);//null 是互斥体的名字可以是任何值

         public static void Add()

         {

              mutex.WaitOne();

              Program .student.Add(new students ());

              Console .WriteLine(" 现在学校里有{0} :名学生" , Program .student.Count);

             mutex.ReleaseMutex();

         }

         public static void Reduce()

         {

mutex.WaitOne();// 保证了在该线程没有ReleaseMutex 之前没有其他线程可以对Program.student 进行访问

              Program .student.RemoveAt(Program .student.Count-1);

                   Console .WriteLine(" 现在学校里有{0} :名学生" , Program .student.Count);

              mutex.ReleaseMutex();

         }

     }

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值