????2. ??? Barrier ?????
?????????????????????????????????????????? Wait ?? Pulse ???????????FrameWork 4.0??????汾????????? Barrier ??????????? Wait / Pulse ?????????????????????????????????
class Program
{
private static Barrier _barrier;
private static void Main(string[] args)
{
var fileNames = new List<string> { "A"?? "B"?? "C"?? "D" };
// ????????????
fileNames.ForEach(name =>
{
if (!File.Exists(name))
File.Create(name).Close();
else
{
using (var sw = new StreamWriter(name))
sw.Write("");
}
});
// ??_barrier?????SignalAndWait??????????????????????????4??
_barrier = new Barrier(4);
_sws = fileNames.Select(File.AppendText).ToList();
// ????????4????????????
var threads = new List<Thread> {
new Thread(() => Work(1))?? new Thread(() => Work(2))?? new Thread(() => Work(3))?? new Thread(() => Work(4))
};
threads.ForEach(t => t.Start());
// ?????????????? StreamWrite
threads.ForEach(t => t.Join());
Console.WriteLine("????????");
_sws.ForEach(sw => sw.Close());
}
static void Work(int threadIndex)
{
var next = threadIndex - 1;
for (int i = 0; i < 100; i++)
{
var sw = _sws[next];
lock (sw)
{
sw.Write(threadIndex);
}
_barrier.SignalAndWait();
next = (next - 1) < 0 ? 3 : next - 1;
}
}
}
???????????? Barrier ???????4???????????????? SignalAndWait ?????????????????????????4?Ρ??????????????ζ??4????????????????????????????????????? Barrier ??