线程同步问题,谁帮忙看一下代码,急需

harrysucceed 2009-03-17 02:51:50
我想实现的目的是同时创建5个并发执行的线程,当一个执行完后下一个才可以进入,但有时一次进去6个,最让我头疼的,哪位麻烦帮改改!!!
class Program
{
private static int numThreads = Convert.ToInt32(Console.ReadLine()); //输入一大于五的数
private static int poolFlag = 0;
private static Mutex mut = new Mutex();
private const int numIterations = 1;
//private const int numThreads;
private const int maxThread = 4;//可执行线程最大数量
private static int j = 0;
static void Main(string[] args)
{
Console.WriteLine("可执行的文件数是:{0}",numThreads);
while ( j < numThreads)
{
if (poolFlag < maxThread & numThreads > 5)
{
Thread myThread = new Thread(new ThreadStart(MyThreadProc));
myThread.Name = String.Format("Thread{0}", j + 1);
j++;
myThread.Start();

}

}

}

private static void MyThreadProc()
{
mut.WaitOne();
Interlocked.Increment(ref poolFlag);
Console.WriteLine("{0} has entered the protected area, poolFlag is {1}",
Thread.CurrentThread.Name, poolFlag);
mut.ReleaseMutex();// Release the Mutex.
Thread.Sleep(1000);
Interlocked.Decrement(ref poolFlag);
Console.WriteLine("{0} is leaving the protected area, poolFlag is {1}",
Thread.CurrentThread.Name, poolFlag);
Console.ReadLine();
}
}
...全文
112 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
无天 2009-06-03
  • 打赏
  • 举报
回复
互斥,临界区,同步。这些方法都可以的。
chinese_zmm 2009-06-03
  • 打赏
  • 举报
回复
private static Mutex mut = new Mutex();
可以换成
private static AutoResetEvent mut = new AutoResetEvent(false);
这个在释放以后可以直接重置
  • 打赏
  • 举报
回复

static object obj = new object();//新建个静态对象
private static void MyThreadProc()
{
lock(obj)//线程执行该方法时锁定对象,如果有其他线程要访问该对象必须等该对象被释放以后
{
mut.WaitOne();
Interlocked.Increment(ref poolFlag);
Console.WriteLine("{0} has entered the protected area, poolFlag is {1}",
Thread.CurrentThread.Name, poolFlag);
mut.ReleaseMutex();// Release the Mutex.
Thread.Sleep(1000);
Interlocked.Decrement(ref poolFlag);
Console.WriteLine("{0} is leaving the protected area, poolFlag is {1}",
Thread.CurrentThread.Name, poolFlag);
Console.ReadLine();
}
}
zenowolf 2009-06-03
  • 打赏
  • 举报
回复
Mutex 控制线程同步么?
hecker728 2009-06-03
  • 打赏
  • 举报
回复
thread.Join();
用这个很适合你。参考msdn的解释和例子
jzywh 2009-03-19
  • 打赏
  • 举报
回复
既然是顺序执行那还开那么多并行线程干什么?

开一个线程,然后在线程里面for循环5次就应该能满足你的需求了

111,126

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Creator Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧