Home   Cover Cover Cover Cover
 

Print server (extension)

Chap4_Ex11.cs
using System;
using System.Threading;
using System.Collections;

/** A printjob
 */
public class Job {
  private string name;
  private int pages;

  public Job(string n, int p) {
    this.name = n;
    this.pages = p;
  }

  public string Name {
    get { return name; }
    set { name = value; }
  }

  public int Pages {
    get { return pages; }
    set { pages = value; }
  }
}

public class PrintServer {
  public static int MINDELAY = 500;
  public static int RANDELAY = 1000;
  public static int MAXPAGES = 50;
  private Queue q;
  private Thread t;
  private bool running = true;

  public PrintServer() {
    q = new Queue();
  }

  public void Start() {
    t = new Thread(new ThreadStart(GenerateRandomJobs));
    t.Start();
  }

  public void AddJob(Job j) {
    Monitor.Enter(q);
    q.Enqueue(j);
    Console.WriteLine("Job: {0} with pages: {1} added to the queue", j.Name, j.Pages);
    Monitor.PulseAll(q);
    Monitor.Exit(q);
  }

  public Job GetNextJob() {
    Monitor.Enter(q);
    while(q.Count==0) Monitor.Wait(q);
    Job j = (Job) q.Dequeue();
    Monitor.PulseAll(q);
    Monitor.Exit(q);
    return j;
  }

  public void GenerateRandomJobs() {
    int nr = 0;
    while(running) {
      System.Random r = new Random(DateTime.Now.Millisecond);
      Job j = new Job("jobNr_"+nr, r.Next(MAXPAGES));
      this.AddJob(j);
      nr++;
      Thread.Sleep(MINDELAY+r.Next(RANDELAY));
    }
  }

  public bool Running {
    get { return running; }
    set { running = value; }
  }  
}

public class Printer {
  private static int TIME_PER_PAGE = 20;
  private string name;
  private Thread t;
  private PrintServer ps;
  private bool running = true;

  public Printer(string n, PrintServer ps) {
    name = n;
    this.ps = ps;
  }

  public void Start() {
    t = new Thread(new ThreadStart(Print));
    t.Start();
  }

  public void Print() {
    // processing of print jobs
    while(running) {
      Job j = ps.GetNextJob();
      Thread.Sleep(j.Pages*TIME_PER_PAGE);
      Console.WriteLine("Printer {0} finished to print: {1}", name, j.Name);
    }
  }

  public bool Running {
    get { return running; }
    set { running = value; }
  }

}

public class Cap4_Ex11_Test {

  public static void Main(string[] args) {
    PrintServer ps = new PrintServer();
    ps.Start();
    Printer[] p = new Printer[3];
    for(int i=0;i<3;i++) {
      p[i] = new Printer("Printer_"+i,ps);
      p[i].Start();
    }
    Console.ReadLine();
    ps.Running = false;
    for(int i=0;i<3;i++) p[i].Running = false;
  }
}