Advertisement
Guest User

Untitled

a guest
Jul 1st, 2016
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.14 KB | None | 0 0
  1. // Adult.cs
  2. public class Adult : Person {
  3.   private List<Child> children = new List<Child>();
  4.   private object _sync = new object();
  5.   private IChildPolicy policy;
  6.  
  7.   public Adult(String name, IChildPolicy policy) {
  8.     this.policy = policy;
  9.     this.name = name;
  10.   }
  11.  
  12.   public IEnumerable<Child> Children { get { return children; } }
  13.   public void AddChild(Child c) {
  14.     children.Add(c);
  15.     c.OnActionRequest += HandleRequest;
  16.   }
  17.   public void ChangePolicy(IChildPolicy cp) { this.policy = cp; }
  18.  
  19.   public void HandleRequest(object child, ChildEventArgs eargs) {
  20.     // it would be better to invoke in Child's thread
  21.     // but we lack the time?
  22.     if(policy.Decide(child))
  23.       eargs.Allow();
  24.     else
  25.       eargs.Deny();
  26.   }
  27. }
  28. // Child.cs
  29. public class ChildEventArgs : EventArgs {
  30.   bool allowed = false;
  31.   int votes = 0;
  32.   public void Deny() {
  33.     lock(this) ++votes;
  34.     Monitor.Pulse();
  35.   }
  36.   public void Allow() {
  37.     lock(this) {
  38.       allowed = true;
  39.       ++votes;
  40.       Monitor.Pulse();
  41.     }
  42.   }
  43. }
  44.  
  45. public class Child : Person {
  46.   // Looking forward for genetic engineering
  47.   private List<Adult> parents = new List<Adult>();
  48.   private System.Action act;
  49.  
  50.   public delegate void ChildEventHandler(object sender, ChildEventArgs eargs);
  51.   public event ChildEventHandler OnActRequest;
  52.  
  53.   public Child(IEnumerable<Adult> parents, System.Action act) {
  54.     this.parents.AddRange(parents);
  55.     this.act = act;
  56.   }
  57.  
  58.  
  59.   public IEnumerable<Adult> Parents { get { return parents; } }
  60.   public void Action() {
  61.     if(OnActRequest != null) {
  62.       var eargs = new ChildEventArgs();
  63.       OnActRequest(this, eargs);
  64.       lock(eargs) {
  65.         while(!eargs.allowed && eargs.votes < parents.Length)
  66.           Monitor.Wait(eargs);
  67.         if (eargs.allowed)
  68.           act();
  69.       }
  70.     }
  71.   }
  72. }
  73.  
  74. public interface IChildPolicy {
  75.   bool Decide(Child c);
  76. }
  77. public class BernoulliPolicy : ChildPolicy {
  78.   private static Random rnd = new Random();
  79.  
  80.   private float p;
  81.  
  82.   public BernoullyPolicy(float p=.5) {
  83.     this.p = p;
  84.   }
  85.   public bool Decide(Child c) {
  86.     return (rnd.NextDouble() < p);
  87.   }
  88. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement