IF it in "only" double enter/leave....
You could use some logging, with indent.
Then if you log like
->Enter called by "foo"
-->Enter called by "bar"
--<Leave called by
You would see, where it becomes unbalanced. With too many enters the indent will grow.
You do need to log from where it was called. Then you can count
- how often each caller did enter,
- and how often each caller did leave
You can do that without the indent too...
But to many Enter will not Deadlock.
They will just lock all other threads. The thread that did (over-)enter will keep going.
Deadlocks often happen due to: Wrong lock order.
If you have more than one lock (more than one critical section object.
And you have sometimes:
Lock1.Enter;
Lock2.Enter;
and other times
Lock2.Enter;
Lock1.Enter;
Then you can get
Thread-1: Lock1.Enter;
Thread-2: Lock2.Enter;
Thread-2: Lock1.Enter; // wait....
Thread-1: Lock2.Enter; // wait..., and since Thread2 waits for Lock1, it wont ever become available
All locks must always enter in the same order.
In the above example, you could in Lock1 (when it is entered non-nested) add a check, that lock2 has not been entered (by the same thread).
Using "threadvar" you can for each lock have a variable that counts, if that lock has been entered by the current thread.
If you are on Linux, there is a great tool called valgrind.
It has 2 very similar tools to analyse your threaded code.
https://valgrind.org/docs/manual/hg-manual.htmlhttps://valgrind.org/docs/manual/drd-manual.htmlHowever, reading and understanding the output of those 2 tools requires time. (And googling).
And, it requires to filter out a lot of false positives.
Also, it does NOT tell you when you enter to often. It can tell you when you Leave to often.
And it can tell you, when you get the order mixed up.