From: Sean O'Halpin Date: 2013-02-24T23:12:29+09:00 Subject: Re: Ruby Multithreaded producer-consumer problem On Sun, Feb 24, 2013 at 1:30 AM, Abhijit Sarkar wrote: > Bump! > A problem unsolved keeps bugging me, I seriously hope the great minds > here would have something for me. > Hi, I've created a gist at https://gist.github.com/seanohalpin/5023887 which attempts to make your program do what I think it's trying to do. I've tried to keep as close to your original as possible so you can see the differences more easily. There are other things I would change but they are not relevant to this discussion. This is running on ruby 1.9.3p194. A couple of points: - it's really not clear what you're trying to do - a problem definition would help. - as Robert pointed out, using Thread.abort_on_exception = true would help. You would have found that Math does not have a rand method for example. - the only shared state you need to protect access to is the @orange_count variable - it's unnecessary to use synchronize around the whole loop. Also, that logic would probably be better encapsulated in the OrangeTree class itself. - you don't check whether the exit condition for the orange_picker thread is true before waiting on the CV. This will halt your thread indefinitely when the age_increaser thread exits before the orange_picker thread starts the wait. Multiple checking of conditions is an unfortunate but necessary aspect of multi-threaded programming with mutexes, etc. - lastly, before you go down the rabbit hole of mutexes and condition variables, I would strongly advise you adopt the Actor model to isolate access to state and use queues to communicate between threads. You will save yourself a world of pain. BTW Tony's advice to look at DCell is good advice! Regards, Sean