问题描述
黑白子分拣问题:有2个线程,一个专拣黑子,另一个专拣白子,每次只能拣一子。
用C#的同步和互斥机制实现,2个白子、1个黑子交替的分拣方案。
问题分析
Semaphore(信号量)两个:black,white。
Thread(线程)两个:Black,White。
代码实现
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace 黑白子分拣
{
class Program
{
private static Semaphore black,white;
private static int count = 0;
static void Main(string[] args)
{
black = new Semaphore(0, 1);
white = new Semaphore(1, 1);
Thread b = new Thread(Black);
Thread w = new Thread(White);
w.Start();
b.Start();
}
protected static void Black()
{
for (; ; )
{
black.WaitOne();
Console.WriteLine("拣到一个黑子");
Thread.Sleep(500);
white.Release();
}
}
protected static void White()
{
for (; ; )
{
white.WaitOne();
Console.WriteLine("拣到一个白子");
Thread.Sleep(500);
count++;
if (count%2==0)
{
black.Release();
}
else
{
white.Release();
}
}
}
}
}