多个线程,期望其中某一个线程因为某一种原因发出线程阻塞操作,使得别的线程在当前执行循环或下一个执行循环时进入阻塞状态,直到这个发起线程把问题处理完成后发出解除阻塞为止。
以下代码在前期没什么问题,经过几次循环后就不行了。
using System; using System.Diagnostics; using System.Threading; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Thread[] threads = new Thread[2]; for (int i = 0; i < threads.Length; i++) { threads[i] = new Thread(new ParameterizedThreadStart(Run)); threads[i].Start(i); } } private static string uniqueID = "unique name"; private static void Run(object state) { while (true) { bool createdNew; using (System.Threading.Mutex mutex = new System.Threading.Mutex(true, uniqueID, out createdNew)) { if (!createdNew) { //如果互斥对象被别的线程构建,等待互斥对象被释放 Console.WriteLine("Thread {0} Entry Wating...", state); Debug.WriteLine("Thread {0} Entry Wating...", state); mutex.WaitOne(); Console.WriteLine("Thread {0} Exit Wating...", state); Debug.WriteLine("Thread {0} Exit Wating...", state); } } int working = new Random().Next(1000, 3000); Console.WriteLine("Thread {0} Do Something for {1}...", state, working); Debug.WriteLine("Thread {0} Do Something for {1}...", state, working); Thread.Sleep(working); Console.WriteLine("Thread {0} Do Something ok for {1}...", state, working); Debug.WriteLine("Thread {0} Do Something ok for {1}...", state, working); bool critical = new Random().Next(1000, 3000) % 10 == 0; if (critical) { Console.WriteLine("Thread {0} Entry critical...", state); while (true) { using (System.Threading.Mutex mutex = new System.Threading.Mutex(true, uniqueID, out createdNew)) { if (!createdNew) { //如果互斥对象被别的线程构建,等待互斥对象被释放 Console.WriteLine("Thread {0} Entry Wating for critical...", state); Debug.WriteLine("Thread {0} Entry Wating for critical...", state); mutex.WaitOne(); Console.WriteLine("Thread {0} Exit Wating for critical...", state); Debug.WriteLine("Thread {0} Exit Wating for critical...", state); } else { working = new Random().Next(1000, 3000); Console.WriteLine("Thread {0} Do critical Something for {1}...", state, working); Debug.WriteLine("Thread {0} Do critical Something for {1}...", state, working); Thread.Sleep(working); Console.WriteLine("Thread {0} Do critical Something ok for {1}...", state, working); Debug.WriteLine("Thread {0} Do critical Something ok for {1}...", state, working); mutex.ReleaseMutex(); break; } } } } } } } }
这个问题描述得不够详细
很清楚了吧?就是多个线程并行,每个线程都有可能遇到一些特殊原因,当这样的特殊原因(可能是临界资源,也可能是灾难性故障)发生的时候,别的线程就必须进入暂停状态(由故障产生或发现线程发起暂停消息),然后等待发起线程把问题处理完成后发出解锁信息,从而使得别的线程继续运行。
我把代码补充上来,不知道怎么没代码了。
@笨笨蜗牛: 有没有考虑过使用Task?
@笨笨蜗牛: 首页有一篇不错的多线程方面的文章 —— C# 温故而知新: 线程篇(一)