Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Adult.cs
- public class Adult : Person {
- private List<Child> children = new List<Child>();
- private object _sync = new object();
- private IChildPolicy policy;
- public Adult(String name, IChildPolicy policy) {
- this.policy = policy;
- this.name = name;
- }
- public IEnumerable<Child> Children { get { return children; } }
- public void AddChild(Child c) {
- children.Add(c);
- c.OnActionRequest += HandleRequest;
- }
- public void ChangePolicy(IChildPolicy cp) { this.policy = cp; }
- public void HandleRequest(object child, ChildEventArgs eargs) {
- // it would be better to invoke in Child's thread
- // but we lack the time?
- if(policy.Decide(child))
- eargs.Allow();
- else
- eargs.Deny();
- }
- }
- // Child.cs
- public class ChildEventArgs : EventArgs {
- bool allowed = false;
- int votes = 0;
- public void Deny() {
- lock(this) ++votes;
- Monitor.Pulse();
- }
- public void Allow() {
- lock(this) {
- allowed = true;
- ++votes;
- Monitor.Pulse();
- }
- }
- }
- public class Child : Person {
- // Looking forward for genetic engineering
- private List<Adult> parents = new List<Adult>();
- private System.Action act;
- public delegate void ChildEventHandler(object sender, ChildEventArgs eargs);
- public event ChildEventHandler OnActRequest;
- public Child(IEnumerable<Adult> parents, System.Action act) {
- this.parents.AddRange(parents);
- this.act = act;
- }
- public IEnumerable<Adult> Parents { get { return parents; } }
- public void Action() {
- if(OnActRequest != null) {
- var eargs = new ChildEventArgs();
- OnActRequest(this, eargs);
- lock(eargs) {
- while(!eargs.allowed && eargs.votes < parents.Length)
- Monitor.Wait(eargs);
- if (eargs.allowed)
- act();
- }
- }
- }
- }
- public interface IChildPolicy {
- bool Decide(Child c);
- }
- public class BernoulliPolicy : ChildPolicy {
- private static Random rnd = new Random();
- private float p;
- public BernoullyPolicy(float p=.5) {
- this.p = p;
- }
- public bool Decide(Child c) {
- return (rnd.NextDouble() < p);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement