A synchronized shared buffer implementation

image_pdfimage_print

using System;
using System.Threading;

public class SynchronizedBuffer
{
private int buffer = -1;

private int occupiedBufferCount = 0;

public int Buffer
{
get
{
Monitor.Enter( this );

if ( occupiedBufferCount == 0 )
{
Console.WriteLine(Thread.CurrentThread.Name + ” tries to read.” );
DisplayState( “Buffer empty. ” +Thread.CurrentThread.Name + ” waits.” );
Monitor.Wait( this );
}
–occupiedBufferCount;

DisplayState( Thread.CurrentThread.Name + ” reads ” + buffer );

Monitor.Pulse( this );
int bufferCopy = buffer;

Monitor.Exit( this );

return bufferCopy;
}
set
{
Monitor.Enter( this );
if ( occupiedBufferCount == 1 )
{
Console.WriteLine(Thread.CurrentThread.Name + ” tries to write.” );
DisplayState( “Buffer full. ” + Thread.CurrentThread.Name + ” waits.” );
Monitor.Wait( this );
}
buffer = value;

++occupiedBufferCount;

DisplayState( Thread.CurrentThread.Name + ” writes ” + buffer );
Monitor.Pulse( this );

Monitor.Exit( this );
}
}

public void DisplayState( string operation )
{
Console.WriteLine( “{0,-35}{1,-9}{2}
“,operation, buffer, occupiedBufferCount );
}

static void Main( string[] args )
{
SynchronizedBuffer shared = new SynchronizedBuffer();
Random random = new Random();

Console.WriteLine( “{0,-35}{1,-9}{2}
“,”Operation”, “Buffer”, “Occupied Count” );
shared.DisplayState( “Initial state” );

Producer producer = new Producer( shared, random );
Consumer consumer = new Consumer( shared, random );

Thread producerThread = new Thread( new ThreadStart( producer.Produce ) );
producerThread.Name = “Producer”;

Thread consumerThread = new Thread( new ThreadStart( consumer.Consume ) );
consumerThread.Name = “Consumer”;

producerThread.Start();
consumerThread.Start();
}
}

public class Consumer
{
private SynchronizedBuffer sharedLocation;
private Random randomSleepTime;

public Consumer( SynchronizedBuffer shared, Random random )
{
sharedLocation = shared;
randomSleepTime = random;
}

public void Consume()
{
int sum = 0;

for ( int count = 1; count <= 10; count++ ) { Thread.Sleep( randomSleepTime.Next( 1, 1001 ) ); sum += sharedLocation.Buffer; } Console.WriteLine("{0} read values totaling: {1}. Terminating {0}.",Thread.CurrentThread.Name, sum ); } } public class Producer { private SynchronizedBuffer sharedLocation; private Random randomSleepTime; public Producer( SynchronizedBuffer shared, Random random ) { sharedLocation = shared; randomSleepTime = random; } public void Produce() { for ( int count = 1; count <= 10; count++ ) { Thread.Sleep( randomSleepTime.Next( 1, 1001 ) ); sharedLocation.Buffer = count; } Console.WriteLine( "{0} done producing. Terminating {0}.",Thread.CurrentThread.Name ); } } [/csharp]

Thread sleep demo

image_pdfimage_print


   

   using System;
   using System.Threading;

   class ThreadTester
   {
      static void Main( string[] args )
      {
         MessagePrinter printer1 = new MessagePrinter();
         Thread thread1 = new Thread ( new ThreadStart( printer1.Print ) );
         thread1.Name = "thread1";

         MessagePrinter printer2 = new MessagePrinter();
         Thread thread2 = new Thread ( new ThreadStart( printer2.Print ) );
         thread2.Name = "thread2";

         MessagePrinter printer3 = new MessagePrinter();
         Thread thread3 = new Thread ( new ThreadStart( printer3.Print  ) );
         thread3.Name = "thread3";

         Console.WriteLine( "Starting threads" );

         thread1.Start();
         thread2.Start();
         thread3.Start();

         Console.WriteLine( "Threads started
" ); 

      } 
   }
   class MessagePrinter {
      public void Print() 
      {
         Thread current = Thread.CurrentThread; 
         Console.WriteLine(current.Name + " going to sleep" );
         Thread.Sleep ( 4000 );
         Console.WriteLine( current.Name + " done sleeping" );
      } 
   }



           
          


Use IsAlive to wait for threads to end

image_pdfimage_print
   

/*
C#: The Complete Reference 
by Herbert Schildt 

Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
using System;

// Use IsAlive to wait for threads to end. 
public class MoreThreads2 { 
  public static void Main() { 
    Console.WriteLine("Main thread starting."); 
 
    // Construct three threads. 
    MyThread mt1 = new MyThread("Child #1"); 
    MyThread mt2 = new MyThread("Child #2"); 
    MyThread mt3 = new MyThread("Child #3"); 
 
    do { 
      Console.Write("."); 
      Thread.Sleep(100); 
    } while (mt1.thrd.IsAlive &amp;&amp; 
             mt2.thrd.IsAlive &amp;&amp; 
             mt3.thrd.IsAlive); 
 
    Console.WriteLine("Main thread ending."); 
  } 
}


           
          


Current Thread Properties

image_pdfimage_print

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

class Program {
static int interval;
static void Main(string[] args) {
interval = 100;

ThreadPool.QueueUserWorkItem(new WaitCallback(StartMethod));
Thread.Sleep(100);
ThreadPool.QueueUserWorkItem(new WaitCallback(StartMethod));
Console.ReadLine();

}

static void StartMethod(Object stateInfo) {
DisplayNumbers(“Thread ” + DateTime.Now.Millisecond.ToString());
Console.WriteLine(“Thread Finished”);
}

static void DisplayNumbers(string GivenThreadName) {
Console.WriteLine(“Starting thread: ” + GivenThreadName);

for (int i = 1; i <= 8 * interval; i++) { if (i % interval == 0) { Console.WriteLine("Count has reached " + i); Console.WriteLine("CurrentCulture: " + Thread.CurrentThread.CurrentCulture.ToString()); Console.WriteLine("IsThreadPoolThread: " + Thread.CurrentThread.IsThreadPoolThread.ToString()); Console.WriteLine("ManagedThreadId: " + Thread.CurrentThread.ManagedThreadId.ToString()); Console.WriteLine("Priority: " + Thread.CurrentThread.Priority.ToString()); Console.WriteLine("ThreadState: " + Thread.CurrentThread.ThreadState.ToString()); Thread.Sleep(1000); } } } } [/csharp]

Thread Pool Tcp Server

image_pdfimage_print
   

/*
C# Network Programming 
by Richard Blum

Publisher: Sybex 
ISBN: 0782141765
*/
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

public class ThreadPoolTcpSrvr
{
   private TcpListener client;

   public ThreadPoolTcpSrvr()
   {
      client = new TcpListener(9050);
      client.Start();

      Console.WriteLine("Waiting for clients...");
      while(true)
      {
         while (!client.Pending())
         {
            Thread.Sleep(1000);
         }
         ConnectionThread newconnection = new ConnectionThread();
         newconnection.threadListener = this.client;
         ThreadPool.QueueUserWorkItem(new
                    WaitCallback(newconnection.HandleConnection));
      }
   }

   public static void Main()
   {
      ThreadPoolTcpSrvr tpts = new ThreadPoolTcpSrvr();
   }
}

class ConnectionThread
{
   public TcpListener threadListener;
   private static int connections = 0;

   public void HandleConnection(object state)
   {
      int recv;
      byte[] data = new byte[1024];

      TcpClient client = threadListener.AcceptTcpClient();
      NetworkStream ns = client.GetStream();
      connections++;
      Console.WriteLine("New client accepted: {0} active connections",
                         connections);

      string welcome = "Welcome to my test server";
      data = Encoding.ASCII.GetBytes(welcome);
      ns.Write(data, 0, data.Length);

      while(true)
      {
         data = new byte[1024];
         recv = ns.Read(data, 0, data.Length);
         if (recv == 0)
            break;
      
         ns.Write(data, 0, recv);
      }
      ns.Close();
      client.Close();
      connections--;
      Console.WriteLine("Client disconnected: {0} active connections",
                         connections);
   }
}

           
          


ThreadPool.QueueUserWorkItem

image_pdfimage_print

using System;
using System.Threading;

class WinterLocked {
public ManualResetEvent a = new ManualResetEvent(false);
private int i = 5;

public void Run(object s) {
Interlocked.Increment(ref i);
Console.WriteLine(“{0} {1}”,
Thread.CurrentThread.GetHashCode(), i);
}
}

public class MainApp {
public static void Main() {
ManualResetEvent mR = new ManualResetEvent(false);
WinterLocked wL = new WinterLocked();
for (int i = 1; i <= 10; i++) { ThreadPool.QueueUserWorkItem(new WaitCallback(wL.Run), 1); } mR.WaitOne(10000, true); } } [/csharp]

ThreadPool.RegisterWaitForSingleObject

image_pdfimage_print
   
 
using System;
using System.Threading;

class MainClass
{
    private static void EventHandler(object state, bool timedout)
    {
        if (timedout)
        {
            Console.WriteLine("{0} : Wait timed out.", DateTime.Now.ToString("HH:mm:ss.ffff"));
        }
        else
        {
            Console.WriteLine("{0} : {1}", DateTime.Now.ToString("HH:mm:ss.ffff"), state);
        }
    }

    public static void Main()
    {
        AutoResetEvent autoEvent = new AutoResetEvent(false);
        string state = "AutoResetEvent signaled.";
        RegisteredWaitHandle handle = ThreadPool.RegisterWaitForSingleObject(autoEvent, EventHandler, state, 3000, false);

        while (Console.ReadLine().ToUpper() != "CANCEL")
        {
            autoEvent.Set();
        }
        Console.WriteLine("Unregistering wait operation.");
        handle.Unregister(null);
    }
}