我的学校任务是构建具有相同循环延迟但使用信号量更快地运行任务的代码。这是用于学习信号量的。 我制作了如下脚本,但是两个相似线程之间的延迟为1.4秒。有没有一种方法可以通过调整信号量来使程序运行更快。
using System;
using System.Threading;
using System.Diagnostics;
//Example in using sleep() and Threads in C#
namespace ThreadSys
{
class ThreadClass
{
int loopDelay, loopCnt;
Thread cThread;
static Semaphore _sem = new Semaphore(1, 5);
public ThreadClass(string name, int delay)
{
loopCnt = 0;
loopDelay = delay;
cThread = new Thread(new ThreadStart(this.run));
cThread.Name = name;
cThread.Start();
}
// The main function in the ThreadClass
void run()
{
do
{
_sem.WaitOne();
Console.Write(cThread.Name + ":" + DateTime.Now.ToString(" HH:mm:ss.fff "));
Console.Write(cThread.Name + ":" + " Hello ");
Console.Write(cThread.Name + ":" + " A number ");
Console.Write(cThread.Name + ":" + " Year ");
Console.WriteLine();
Thread.Sleep(loopDelay);
loopCnt++;
_sem.Release();
} while (loopCnt < 40);
Console.WriteLine(cThread.Name + "*Finished* ");
}
}
// The application
class ThreadSys
{
static void Main(string[] args)
{
ThreadClass dt1 = new ThreadClass("[T1]", 95);
ThreadClass dt2 = new ThreadClass("[T2]", 191);
ThreadClass dt3 = new ThreadClass("[T3]", 287);
ThreadClass dt4 = new ThreadClass("[T4]", 383);
ThreadClass dt5 = new ThreadClass("[T5]", 479);
}
}
}