博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Mutex
阅读量:4588 次
发布时间:2019-06-09

本文共 3461 字,大约阅读时间需要 11 分钟。

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

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

所以在线程同步角度来说,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\r\n",             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("\n当前时间:{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);            }        }    }

 

转载于:https://www.cnblogs.com/y112102/p/3723512.html

你可能感兴趣的文章
两个被混淆的单词property和attribute
查看>>
MySQL存储过程
查看>>
第四周作业
查看>>
VS2010安装包制作过程
查看>>
第十一周进度总结
查看>>
python机器学习——分词
查看>>
PHP5 mysqli 教程
查看>>
C#与Java 详细比较
查看>>
Ubuntu下安装和配置Apache2
查看>>
arm寄存器解析
查看>>
解决ScrollView嵌套RecyclerView的显示及滑动问题
查看>>
洛谷 P3384 【模板】树链剖分
查看>>
Android下移植tcpflow
查看>>
python中元组与列表的区别
查看>>
UFT demo(一)
查看>>
深入理解JAVA I/O系列三:字符流详解
查看>>
Javascript编程风格
查看>>
Django 知识点补充
查看>>
iOS开发>学无止境 - Cell异步图片加载优化,缓存机制详解
查看>>
博客第六天
查看>>