C#多线程和互斥:不等待释放

时间:2014-04-02 10:33:01

标签: c# .net multithreading mutex

我试图使用Mutex来获取3个线程之间的共享信息。

这是共享类:

public class SharedMemory
{
    public Mutex mutex;
    protected static int sharedInfo;

    public SharedMemory()
    {
        mutex = new Mutex(false);
        sharedInfo = 0;
    }

    public void StartProcessing()
    {
        // Init objects
        AlertSender sender1 = new AlertSender("T1", 12, 5);
        AlertSender sender2 = new AlertSender("T2", 30, 5);
        AlertSender sender3 = new AlertSender("T3", 5, 8);

        // Init Threads
        List<Thread> threads = new List<Thread>();

        Thread temp;
        temp = new Thread(new ThreadStart(sender1.BetaTest));
        temp.Name = "T1";
        threads.Add(temp);
        temp = new Thread(new ThreadStart(sender2.BetaTest));
        temp.Name = "T2";
        threads.Add(temp);
        temp = new Thread(new ThreadStart(sender3.BetaTest));
        temp.Name = "T3";
        threads.Add(temp);

        foreach (Thread t in threads)
        {
            Console.WriteLine(string.Format("Thread '{0}' - pId : {1}", t.Name, t.ManagedThreadId));
        }

        foreach (Thread t in threads)
        {
            t.Start();
        }

        Console.WriteLine("Main program has finished !");
        Console.WriteLine("Press ENTER to end...");
        Console.ReadLine();

        foreach (Thread t in threads)
        {
            t.Abort();
        }
    }
}

然后是Thread&#39; AlertSender&#39;代码:

class AlertSender : SharedMemory 
{
    private string name;
    private int maxLimit;
    private int delay;

    public AlertSender(string name, int maxLimit, int delay)
    {
        this.name = name;
        this.maxLimit = maxLimit;
        this.delay = delay;
    }

    public void BetaTest()
    {
        Console.WriteLine(string.Format("Thread '{0}' : START", this.name));

        while (sharedInfo < maxLimit)
        {
            Console.WriteLine(string.Format("'{0}' : WAITING", this.name));
            mutex.WaitOne();

            try
            {
                sharedInfo++;
                Console.WriteLine(string.Format("'{0}' HAS THE POWER : {1}. Waiting for {2} seconds...", this.name, sharedInfo, delay));

                Thread.Sleep(delay * 1000);
            }
            finally
            {
                Console.WriteLine(string.Format("'{0}' : RELEASE", this.name));
                mutex.ReleaseMutex();
            }
        }

        Console.WriteLine(string.Format("Thread '{0}' : STOP", this.name));
    }
}

当我运行此代码时,线程正在增加&#34; SharedInfo&#34;即使前一个帖子没有完成&#34; ReleaseMutex&#34;尚未...

知道我做错了什么吗?

感谢您的反馈!

0 个答案:

没有答案