zoukankan      html  css  js  c++  java
  • Mutex

    一个同步基元,也可用于进程间同步。 

    即进程同步 当然也可以线程同步 

    所以在线程同步角度来说,Monitor开销小,优于Mutex,

    要实现进程同步,Monitor也干不了,Mutex是首选。

    MSDN 实例:

    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
    ", 
                Thread.CurrentThread.Name);
    
            // Release the Mutex.
            mut.ReleaseMutex();
        }
    }
        class Program
        {
            static void Main(string[] args)
            {
                for (int i = 0; i < 20; i++)
                {
                    Thread t = new Thread(Run);
    
                    t.Start();
                }
    
                Console.Read();
            }
    
            static int count = 0;
    
            static Mutex mutex = new Mutex();
    
            static void Run()
            {
                Thread.Sleep(100);
    
                mutex.WaitOne();
    
                Console.WriteLine("当前数字:{0}", ++count);
    
                mutex.ReleaseMutex();
            }
        }

    进程同步运行2个exe实例:

        class Program
        {
            static void Main(string[] args)
            {
                Thread t = new Thread(Run);
    
                t.Start();
    
                Console.Read();
            }
    
            static Mutex mutex = new Mutex(false, "tsp");
    
            static void Run()
            {
                mutex.WaitOne();
    
                Console.WriteLine("当前时间:{0}我是线程:{1},我已经进去临界区", DateTime.Now, Thread.CurrentThread.GetHashCode());
    
                Thread.Sleep(10000);
    
                Console.WriteLine("
    当前时间:{0}我是线程:{1},我准备退出临界区", DateTime.Now, Thread.CurrentThread.GetHashCode());
    
                mutex.ReleaseMutex();
            }
        }

    延伸 同理 一个运行程序只希望启动一个实例:

    查看msdn

        public partial class App : System.Windows.Application
        {
            Mutex mutex;
    
            public App()
            {
                this.Startup += new StartupEventHandler(App_Startup);
            }
    
            void App_Startup(object sender, StartupEventArgs e)
            {
                bool ret;
                mutex = new Mutex(false, Process.GetCurrentProcess().ProcessName, out ret);
                if (!ret)
                {
                    MessageBox.Show("程序已打开", "", MessageBoxButton.OK, MessageBoxImage.Stop);
                    Environment.Exit(0);
                }
            }
        }
  • 相关阅读:
    在VS2010下,用C语言编写pthread多线程程序的配置
    java帮助文档系列JDK1.5 JDK1.6 JDK1.7官方中英完整版下载
    瑜伽练习day02----适合练习瑜伽时听的歌曲
    瑜伽练习day01----瑜伽练习的好处,坏处
    抛出错误Debug Assertion Failed!
    stringstream的基本用法
    AWS中S3的Bucket桶访问策略
    AWS中SQS的几项使用注意
    AWS在.Net中连接数据库时发生认证错误的解决办法
    .Net捕捉配置或程序错误
  • 原文地址:https://www.cnblogs.com/y112102/p/3723512.html
Copyright © 2011-2022 走看看