c# - Monitor.Wait() causing elements of the queue to be skipped -
i'm trying pass elements 1 queue next space becomes available. fixedsizequeue example saw here. printing out elements added , removed queue turns out of them skipped. think happens when monitor.wait(queue) called. can me solve this?
class fixedsizequeue<t> : queue<t> { private readonly queue<t> queue = new queue<t>(); private readonly int maxsize; public fixedsizequeue(int maxsize) { this.maxsize = maxsize; } public new void enqueue (t item) { lock (queue) { while (queue.count >= maxsize) { monitor.wait(queue); } queue.enqueue(item); if (queue.count == 1) { // wake blocked dequeue monitor.pulseall(queue); } } } public new t dequeue() { lock (queue) { while (queue.count == 0) { monitor.wait(queue); } t item = queue.dequeue(); if (queue.count == maxsize - 1) { monitor.pulseall(queue); } return item; } } } class program { static void addcustomertowaitinglist(queue<customer> customers, fixedsizequeue<customer> waitinglist) { customer customer = new customer(); (int = 0; < 40; i++) { customer = customers.dequeue(); waitinglist.enqueue(customer); } } static void addcustomertoeatinglist(fixedsizequeue<customer> waitinglist, fixedsizequeue<customer> eatinglist) { customer customer = new customer(); (int = 0; < 40; i++) { customer = waitinglist.dequeue(); eatinglist.enqueue(customer); } } static void removecustomerfromwaitinglist(fixedsizequeue<customer> waitinglist) { customer customer = new customer(); (int = 0; < 40; i++) { customer = waitinglist.dequeue(); } } static void removecustomerfromeatinglist(fixedsizequeue<customer> eatinglist) { customer customer = new customer(); foreach(customer c in eatinglist) { customer = eatinglist.dequeue(); } } static void main(string[] args) { chef chef = new chef(); customer customer = new customer(); queue<customer> customers = new queue<customer>(40); fixedsizequeue<customer> eatinglist = new fixedsizequeue<customer>(7); fixedsizequeue<customer> waitinglist = new fixedsizequeue<customer>(12); thread cafeclock = new thread(new threadstart(cafe.startcounting)); thread addcustomertowaitinglist = new thread(() => addcustomertowaitinglist(customers, waitinglist)); thread removecustomerfromwaitinglist = new thread(() => removecustomerfromwaitinglist(waitinglist)); thread addcustomertoeatinglist = new thread(() => addcustomertoeatinglist(waitinglist,eatinglist)); thread removecustomerfromeatinglist = new thread(() => removecustomerfromeatinglist(eatinglist)); (int = 1; <= 40; i++) { customer.id = i; customers.enqueue(customer); customer = new customer(); } addcustomertowaitinglist.start(); removecustomerfromwaitinglist.start(); addcustomertoeatinglist.start(); removecustomerfromeatinglist.start(); console.writeline("end"); } }
Comments
Post a Comment