Csharp/C Sharp/Thread/Monitor — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
|
(нет различий)
|
Версия 15:31, 26 мая 2010
Monitor: Enter
using System;
using System.Threading;
public class EnterExit {
private int result = 0;
public void NonCriticalSection() {
Console.WriteLine("Entered Thread " + Thread.CurrentThread.GetHashCode());
for (int i = 1; i <= 5; i++) {
Console.WriteLine("Result = " + result++ + " ThreadID "
+ Thread.CurrentThread.GetHashCode());
Thread.Sleep(1000);
}
Console.WriteLine("Exiting Thread " + Thread.CurrentThread.GetHashCode());
}
public void CriticalSection() {
Monitor.Enter(this);
Console.WriteLine("Entered Thread " + Thread.CurrentThread.GetHashCode());
for (int i = 1; i <= 5; i++) {
Console.WriteLine("Result = " + result++ + " ThreadID " +
Thread.CurrentThread.GetHashCode());
Thread.Sleep(1000);
}
Console.WriteLine("Exiting Thread " + Thread.CurrentThread.GetHashCode());
Monitor.Exit(this);
}
public static void Main(String[] args) {
EnterExit e = new EnterExit();
Thread nt1 = new Thread(new ThreadStart(e.NonCriticalSection));
nt1.Start();
Thread nt2 = new Thread(new ThreadStart(e.NonCriticalSection));
nt2.Start();
Thread ct1 = new Thread(new ThreadStart(e.CriticalSection));
ct1.Start();
Thread ct2 = new Thread(new ThreadStart(e.CriticalSection));
ct2.Start();
}
}
Monitor.Pulse
using System;
using System.Threading;
class MessageBoard {
private String messages = "no messages";
public void Reader() {
try {
Monitor.Enter(this);
if (messages == "no messages") {
Console.WriteLine("{0} {1}",Thread.CurrentThread.Name, messages);
Console.WriteLine("{0} waiting",Thread.CurrentThread.Name);
Monitor.Wait(this);
}
Console.WriteLine("{0} {1}",Thread.CurrentThread.Name, messages);
} finally {
Monitor.Exit(this);
}
}
public void Writer() {
try {
Monitor.Enter(this);
messages = "Greetings!";
Console.WriteLine("{0} Done writing message",Thread.CurrentThread.Name);
Monitor.Pulse(this);
} finally {
Monitor.Exit(this);
}
}
public static void Main() {
MessageBoard myMessageBoard = new MessageBoard();
Thread reader = new Thread(new ThreadStart(myMessageBoard.Reader));
reader.Name = "ReaderThread:";
Thread writer = new Thread(new ThreadStart(myMessageBoard.Writer));
writer.Name = "WriterThread:";
reader.Start();
writer.Start();
}
}
Monitor.TryEnter
using System;
using System.Threading;
public class TryEnter {
public void CriticalSection() {
bool b = Monitor.TryEnter(this, 1000);
Console.WriteLine("Thread " +
Thread.CurrentThread.GetHashCode() +
" TryEnter Value " + b);
for (int i = 1; i <= 3; i++) {
Thread.Sleep(1000);
Console.WriteLine(i + " " +
Thread.CurrentThread.GetHashCode() + " ");
}
Monitor.Exit(this);
}
public static void Main() {
TryEnter a = new TryEnter();
Thread t1 = new Thread(new ThreadStart(a.CriticalSection));
Thread t2 = new Thread(new ThreadStart(a.CriticalSection));
t1.Start();
t2.Start();
}
}