Thread Synchronization in C#
using System;
using System.Collections;
using System.Numerics;
using System.Threading;
using System.Threading.Tasks;
namespace CSharp
{
public class Q
{
Queue q = new Queue();
public void put(int n)
{
lock (this)
{
while(q.Count==1)
{
Monitor.Wait(this);
}
q.Enqueue(n);
Monitor.Pulse(this);
}
}
public int get()
{
lock (this)
{
while (q.Count==0)
{
Monitor.Wait(this);
}
int n = (int)q.Dequeue();
Monitor.Pulse(this);
return n;
}
}
}
public class Consumer
{
Q q;
public Consumer(Q q)
{
this.q = q;
new Thread(new ThreadStart(this.Consume)).Start();
}
public void Consume()
{
for (int i=1; i <= 5; i++)
{
int n = q.get();
Console.WriteLine ("Consuming {0}", n);
Thread.Sleep(200);
}
}
}
public class Producer
{
Q q;
public Producer(Q q)
{
this.q = q;
new Thread(new ThreadStart(this.Produce)).Start();
}
public void Produce()
{
for (int i=1; i <= 5; i++)
{
q.put(i);
Console.WriteLine ("Producing {0}", i);
Thread.Sleep(200);
}
}
}
public class Program
{
public static void Main(string[] args)
{
Q q = new Q();
new Producer(q);
new Consumer(q);
}
}
}
No comments:
Post a Comment
Don't be a silent reader...
Leave your comments...
Anu