zoukankan      html  css  js  c++  java
  • .NET多线程小记(7):进程同步Mutex

    互斥体是跨进程的同步,效率非常低

    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Text;
    using System.Threading;
    using System.Diagnostics;
    
    namespace MultiThreadTest
    {
        class Program
        {
    
            const string file=@"C:\TestMutex.txt";
    
            static Mutex mutex = new Mutex(false, "TestMutext");
    
    
            static void Main(string[] args)
            {
                Thread.Sleep(3000);
    
                Do();
    
                mutex.Close();
    
                Console.Read();
                
            }
    
            static void Do()
            {
                long d1 = DateTime.Now.Ticks;
    
                mutex.WaitOne();
    
                long d2=DateTime.Now.Ticks;
    
                Console.WriteLine("After {0}, Process {1} get mutext",
                    (d2 - d1).ToString(), Process.GetCurrentProcess().Id.ToString());
    
                try
                {
                    if (!File.Exists(file))
                    {
                        using (FileStream fs = File.Create(file)) { }
                    }
                    for (int i = 0; i < 5; i++)
                    {
                        using (FileStream fs = File.Open(file, FileMode.Append))
                        {
                            String content = "Process:" + Process.GetCurrentProcess().Id.ToString() + "i:" + i.ToString()
                                + "\r\n";
                            byte[] data = Encoding.Default.GetBytes(content);
    
                            fs.Write(data, 0, data.Length);
                            Thread.Sleep(300);
    
                        }
                    }
                }            
                finally
                {
                    mutex.ReleaseMutex();
                }            
            }
        }   
    }
    
    启动三个进程

    clip_image002

    clip_image004

  • 相关阅读:
    Redis集群启动脚本
    查看表结构
    MySQL删除冗余数据
    Java中的阶乘
    MySQL中IFNULL,ISNULL和NULLIF
    最小化安装CentOS7后要做的30件事情
    VMware的CentOS部署环境
    CentOS 上的 FirewallD 简明指南
    CentOS安装Java环境
    Linux中一些常用的很巧妙的命令
  • 原文地址:https://www.cnblogs.com/cnblogsfans/p/1597454.html
Copyright © 2011-2022 走看看