zoukankan      html  css  js  c++  java
  • Mutex 类

    当两个或更多线程需要同时访问一个共享资源时,系统需要使用同步机制来确保一次只有一个线程使用该资源。Mutex 是同步基元,它只向一个线程授予对共享资源的独占访问权。如果一个线程获取了互斥体,则要获取该互斥体的第二个线程将被挂起,直到第一个线程释放该互斥体。

    可以使用 WaitHandle.WaitOne 方法请求互斥体的所属权。拥有互斥体的线程可以在对 WaitOne 的重复调用中请求相同的互斥体而不会阻止其执行。但线程必须调用 ReleaseMutex 方法同样多的次数以释放互斥体的所属权。Mutex 类强制线程标识,因此互斥体只能由获得它的线程释放。相反,Semaphore 类不强制线程标识。

    如果线程在拥有互斥体时终止,则称此互斥体被放弃。此互斥体被设置为终止状态,下一个等待的线程获得所属权。如果没有线程拥有互斥体,则互斥体状态为终止。从 .NET Framework 2.0 版开始,需要该互斥体的下一个线程将引发 AbandonedMutexException。在 .NET Framework 2.0 版之前,这样不会引发任何异常。

    实例如下:

    // This example shows how a Mutex is used to synchronize access
    // to a protected resource. Unlike Monitor, Mutex can be used with
    // WaitHandle.WaitAll and WaitAny, and can be passed across
    // AppDomain boundaries.

    using System;
    using System.Threading;

    class Test
    {
    // Create a new Mutex. The creating thread does not own the
    // Mutex.
    private static Mutex mut = new Mutex();
    private const int numIterations = 1;
    private const int numThreads = 3;

    static void Main()
    {
    // Create the threads that will use the protected resource.
    for(int i = 0; i < numThreads; i++)
    {
    Thread myThread = new Thread(new ThreadStart(MyThreadProc));
    myThread.Name = String.Format("Thread{0}", i + 1);
    myThread.Start();
    }

    // The main thread exits, but the application continues to
    // run until all foreground threads have exited.
    }

    private static void MyThreadProc()
    {
    for(int i = 0; i < numIterations; i++)
    {
    UseResource();
    }
    }

    // This method represents a resource that must be synchronized
    // so that only one thread at a time can enter.
    private static void UseResource()
    {
    // Wait until it is safe to enter.
    mut.WaitOne();

    Console.WriteLine("{0} has entered the protected area",
    Thread.CurrentThread.Name);

    // Place code to access non-reentrant resources here.

    // Simulate some work.
    Thread.Sleep(500);

    Console.WriteLine("{0} is leaving the protected area\r\n",
    Thread.CurrentThread.Name);

    // Release the Mutex.
    mut.ReleaseMutex();
    }
    }

  • 相关阅读:
    2020-11-07:已知一个正整数数组,两个数相加等于N并且一定存在,如何找到两个数相乘最小的两个数?
    2020-11-06:go中,谈一下调度器。
    Python2和Python3中urllib库中urlencode的使用注意事项
    python爬虫基础
    python自动抢票
    Movist for Mac 1.4.2 破解版 | Mac上好用的视频播放器有哪些?7 款本地视频播放器实测对比
    前端自动化及优化
    移动端库
    jQuery
    JavaScript
  • 原文地址:https://www.cnblogs.com/miaomiaosdad/p/2421440.html
Copyright © 2011-2022 走看看