进程同步

时间:2014-07-05 20:37:56

标签: .net process synchronization mutex

例如,我创建了两个进程(ConsoleApplication2.exe)。他们每个人都将一些文本(“dog”或“cat”)写入同一个文本文件中:c:_threads_laboratory \ data.txt。我想得到一个结果:

  狗笼子,狗笼子,狗笼子,狗笼子   cat
...

狗窝猫

但我明白了:

  狗笼子狗笼子狗狗笼子   dog
cat
dog
cat
dog
dog
dog
  猫
...

为什么我的结果不正确?我该如何解决?

我的进程由Launcher.exe启动:

// Program.cs
// It builds the Launcher.exe
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Launcher {

  class Program {
    static void Main(string[] args) {

      Console.Title = "Launcher";
      String fileFullName = @"c:\_threads_laboratory\data.txt";

      using (Mutex mutex = new Mutex(true, "my_mutex")) {

        if (File.Exists(fileFullName))
          File.Delete(fileFullName);

        Process proc_1 = new Process();
        String exeName = @".\ConsoleApplication2.exe";
        ProcessStartInfo info_1 = new ProcessStartInfo(exeName, "proc_#1 dog");
        proc_1.StartInfo = info_1;
        proc_1.Start();
        Console.WriteLine("proc_#1 started by launcher...");

        Process proc_2 = new Process();
        ProcessStartInfo info_2 = new ProcessStartInfo(exeName, "proc_#2 cat");
        proc_2.StartInfo = info_2;
        proc_2.Start();
        Console.WriteLine("proc #2 started by launcher...");

        mutex.ReleaseMutex();

        proc_1.WaitForExit();
        proc_2.WaitForExit();
      }

      Console.WriteLine("Result in the \"{0}\" file.", fileFullName);
      Console.WriteLine("Press any key for exit...");
      Console.ReadKey();
    }
  }
}

ConsoleApplication2.exe代码:

// Program_2.cs
// It builds the ConsoleApplication2.exe
using System;
using System.Diagnostics;
using System.IO;
using System.Threading;

namespace ConsoleApplication2 {

  class Program_2 {

    static void Main(string[] args) {
      if (2 != args.Length)
        return;

      Console.Title = args[0];

      Mutex mutex = new Mutex(false, "my_mutex");

      String dir = @"c:\_threads_laboratory";
      String file = "data.txt";
      String fullName = Path.Combine(dir, file);
      if (!Directory.Exists(dir))
        Directory.CreateDirectory(dir);
      String text = args[1];
      Int32 counter = 100;

      using (FileStream fs = File.Open(fullName, FileMode.Append,
        FileAccess.Write, FileShare.ReadWrite)) {
        using (StreamWriter sw = new StreamWriter(fs)) {
          while (counter-- > 0) {
            mutex.WaitOne();
            fs.Position = fs.Length;
            sw.WriteLine(text);
            Console.Write("*");
            sw.Flush();
            fs.Flush(true);
            mutex.ReleaseMutex();
            Thread.Sleep(0);
          }
          sw.Close();
        }
        fs.Close();
      }
    }
  }
}

2 个答案:

答案 0 :(得分:1)

我认为你混淆了互斥和事件。 “Mutex”是“Mutually Exclusive”的缩写 - 您的代码只能确保两个进程不会同时写入文件。

你真正想要的是两件事;一种方法让一个进程发出信号表明它已经完成并且现在正在等待另一个进程 - 而另一个事件则反过来。

答案 1 :(得分:0)

你有同步。不同步的结果就像是

docat
g
cat
cat
cadto
g
dog
catdog

cat