【发布时间】:2014-06-17 20:58:36
【问题描述】:
我正在尝试模拟(非常基本和简单的)操作系统进程管理器子系统,我有三个“进程”(工作人员)向控制台写入内容(这是一个示例):
public class Message
{
public Message() { }
public void Show()
{
while (true)
{
Console.WriteLine("Something");
Thread.Sleep(100);
}
}
}
每个工作人员都应该在不同的线程上运行。我现在就是这样做的: 我有一个 Process 类,它的构造函数接受 Action 委托并从中启动一个线程并暂停它。
public class Process
{
Thread thrd;
Action act;
public Process(Action act)
{
this.act = act;
thrd = new Thread(new ThreadStart(this.act));
thrd.Start();
thrd.Suspend();
}
public void Suspend()
{
thrd.Suspend();
}
public void Resume()
{
thrd.Resume();
}
}
在这种状态下,它会等待我的调度程序恢复它,给它一个运行时间片,然后再次挂起它。
public void Scheduler()
{
while (true)
{
//ProcessQueue is just FIFO queue for processes
//MainQueue is FIFO queue for ProcessQueue's
ProcessQueue currentQueue = mainQueue.Dequeue();
int count = currentQueue.Count;
if (currentQueue.Count > 0)
{
while (count > 0)
{
Process currentProcess = currentQueue.GetNext();
currentProcess.Resume();
//this is the time slice given to the process
Thread.Sleep(1000);
currentProcess.Suspend();
Console.WriteLine();
currentQueue.Add(currentProcess);
count--;
}
}
mainQueue.Enqueue(currentQueue);
}
}
问题在于它不能始终如一地工作。它甚至在这种状态下根本不起作用,我必须在worker的Show()方法中的WriteLine之前添加Thread.Sleep(),就像这样。
public void Show()
{
while (true)
{
Thread.Sleep(100); //Without this line code doesn't work
Console.WriteLine("Something");
Thread.Sleep(100);
}
}
我一直在尝试使用 ManualResetEvent 而不是挂起/恢复,它可以工作,但由于该事件是共享的,因此依赖它的所有线程同时唤醒,而我一次只需要一个特定线程处于活动状态。
如果有人可以帮助我弄清楚如何正常暂停/恢复任务/线程,那就太好了。 我正在做的是试图模拟简单的抢先式多任务处理。 谢谢。
【问题讨论】:
-
你不试试线程池吗
-
另一种“干净”的方法究竟是什么?运行您的示例代码并获得预期的结果?这在一般情况下有用吗?
-
@DhavalPatel 我不确定如何在我的情况下具体使用它,乍一看似乎很复杂
-
我建议您将类名从 Process 更改为其他名称,以避免与 Microsoft 的 Process 类产生歧义
-
您可以使用
async、awaitTask.Run()等以及.Net 4.5 中内置的TAP 的其余部分,并将线程控制委托给框架。 msdn.microsoft.com/en-us/magazine/jj991977.aspx
标签: c# multithreading operating-system preemption