我试图了解如何在使用线程时使用信号量。
我有 2 个线程使用相同的资源 - 一个 Arraylist。一种方法将随机温度添加到列表中,另一种方法计算列表的平均温度。
在这种情况下,如何使用信号量属性 Wait 和 Release?以及如何控制计算平均温度的线程在将某些内容添加到我的列表后启动。
这是我的一些代码:
class Temperature
{
private static Random random = new Random();
private static ArrayList buffer = new ArrayList();
static SemaphoreSlim e, b;
public static void Main (string[] args)
{
e = new SemaphoreSlim(6); //how will this work?
b = new SemaphoreSlim(1);
Thread t1 = new Thread (Add);
t1.Start ();
Thread t2 = new Thread (Average);
t2.Start ();
}
public static void Add()
{
int temperature;
for (int i=0; i<50; i++)
{
temperature = random.Next (36, 42);
Console.WriteLine ("Temperature added to buffer: " + temperature);
b.Wait ();
e.Wait ();
buffer.Add(temperature);
b.Release ();
Thread.Sleep (50);
}