On Tue, Mar 8, 2011 at 1:35 PM, Eric J. Holtman <eric@holtmans.com> wrote:
On 3/8/2011 12:29 PM, Igor R wrote:

>
> This is not really the aswer to your question, but if you work with
> MSVC, in case of deadlock you can just push "pause" button and see
> what happens to every thread.

Yeah, that's how I found this latest programming screwup
on my part, attaching the debugger after the application
went silent.

I was just wondering if there was some quick #define to
enable a debugging mode where I'd get an exception or
something I could log when that happened, as opposed to
the program just locking up.


Maybe my experience with multithreading is too limited, but I have generally been successful in preventing deadlock and race conditions by using a blend of analysis and mutex semaphores and counting semaphores.

My approach can be likened to choosing between catching a divide by zero floating point exception and preventing divide by zero errors before they can happen.  For that, a simple check on the divisor is sufficient to both prevent the floating point exception and ensuring the program behaves rationally in those cases that would otherwise produce such an exception.

Similarly, my preference is to make threads relatively isolated, so they don't share resources.  In the circumstance where shared resources are involved, I try to ensure that while any thread can have read access, only one has write access, and that one can be constructed like a server, to listen for write requests, and it handles queuing these requests, and when the shared resource(s) is free, obtains exclusive rights to the resource until all pending writes are complete.

The bottom line is I try to design things in such a way that, with a sensibe architcture and judicious use of the right semaphores, deadlocks and race conditions are prevented, eliminating the need to detect them after the fact.

So, if I can answer a question with a question, is it not possible to always prevent deadlocks and race conditions by careeful analysis and use of the right suite of semaphores, or it is just that my experience with multithreading is too limited to have seen those cases where my approach is insufficient?

Cheers

Ted