c# - ObjectPool implementation deadlocks -


i have implemented generic objectpool class have experienced sometime deadlocks (happens @ monitor.wait(poollock))

can spot error?

public class objectpool<t> t : new() {     private readonly object poollock = new object();     stack<t> stack = null;      public objectpool(int count)     {         stack = new stack<t>(count);         (int i=0; i<count; i++)             stack.push(new t());     }      public t get()     {         lock (poollock)         {             //if no more left wait 1 pushed             while (stack.count < 1)                 monitor.wait(poollock);              return stack.pop();         }     }      public void put(t item)     {         lock (poollock)         {             stack.push(item);             //if adding first send signal             if (stack.count == 1)                 monitor.pulse(poollock);          }     } 

usage

        try         {             service = mypool.get();         }                 {             if (service != null)                 mypool.put(service);         } 

the deadlock happening stack.count > 0 . means have wait/pulse problem. not bad idea call pulse after push(). or @ least when count < 5 or so. remember wait/pulse mechanism not have memory.

a scenario:

thread tries empty pool, , wait()
thread b tries empty pool, , wait()

thread c puts pool, pulse()
thread d puts pool , not pulse (count == 2)

thread activated , gets item.
thread b left waiting. little hope fro recovery.


Comments

Popular posts from this blog

linux - Mailx and Gmail nss config dir -

c# - Is it possible to remove an existing registration from Autofac container builder? -

php - Mysql PK and FK char(36) vs int(10) -