【发布时间】:2019-10-07 21:40:09
【问题描述】:
我目前正在尝试用 C# 实现一个实时多线程软件。我需要3个线程。每个线程执行都必须在截止日期(500µs / 100µs / 50µs)之前完成。线程必须在整个运行时并行运行(直到用户关闭程序)。
有没有一种机制可以保证线程执行不会超过deadline?
这是我的代码:
static void Main(string[] args)
{
Thread thread1 = new Thread(FirstThread);
Thread thread2 = new Thread(SecondThread);
Thread thread3 = new Thread(ThirdThread);
thread1.start();
thread2.start();
thread3.start();
}
static void FirstThread()
{
while(true)
{
SleepMicroSec(500);
}
}
static void SecondThread()
{
while(true)
{
SleepMicroSec(100);
}
}
static void ThirdThread()
{
while(true)
{
SleepMicroSec(50);
}
}
private static void SleepMicroSec(long microSec)
{
var sw = Stopwatch.StartNew();
while (sw.ElapsedTicks / (Stopwatch.Frequency / (1000L * 1000L)) < microSec)
{
}
}
如果达到任务期限,我希望调度程序能够执行上下文切换。
提前感谢您的回答!
【问题讨论】:
-
澄清一下,如果没有达到deadline,你要取消任务吗?
-
“保证”的唯一方法是在每个线程达到其限制并且仍在运行时中止它。在很多情况下,这可能是不可取的......
-
我不想取消任务,只想切换上下文运行另一个任务
-
@bgabriel
I don't want to cancel the task, I just want to switch the context to run another task.因此,如果任务 A 仍在运行并且是时候启动任务 B,您不想中止或终止任务 A,而是要启动任务 B,同时运行两个任务A 和 B 同时? -
@Patrick Tucci 任务应该一个接一个地执行。唯一重要的是它们的执行时间不会超过截止日期
标签: c# multithreading scheduled-tasks multitasking