1 // Copyright (c) 2011-2012 The Bitcoin developers
2 // Distributed under the MIT/X11 software license, see the accompanying
3 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
8 #include <boost/foreach.hpp>
10 #ifdef DEBUG_LOCKORDER
12 // Early deadlock detection.
13 // Problem being solved:
14 // Thread 1 locks A, then B, then C
15 // Thread 2 locks D, then C, then A
16 // --> may result in deadlock between the two threads, depending on when they run.
17 // Solution implemented here:
18 // Keep track of pairs of locks: (A before B), (A before C), etc.
19 // Complain if any thread trys to lock in a different order.
24 CLockLocation(const char* pszName, const char* pszFile, int nLine)
31 std::string ToString() const
33 return mutexName+" "+sourceFile+":"+itostr(sourceLine);
37 std::string mutexName;
38 std::string sourceFile;
42 typedef std::vector< std::pair<void*, CLockLocation> > LockStack;
44 static boost::mutex dd_mutex;
45 static std::map<std::pair<void*, void*>, LockStack> lockorders;
46 static boost::thread_specific_ptr<LockStack> lockstack;
49 static void potential_deadlock_detected(const std::pair<void*, void*>& mismatch, const LockStack& s1, const LockStack& s2)
51 printf("POTENTIAL DEADLOCK DETECTED\n");
52 printf("Previous lock order was:\n");
53 BOOST_FOREACH(const PAIRTYPE(void*, CLockLocation)& i, s2)
55 if (i.first == mismatch.first) printf(" (1)");
56 if (i.first == mismatch.second) printf(" (2)");
57 printf(" %s\n", i.second.ToString().c_str());
59 printf("Current lock order is:\n");
60 BOOST_FOREACH(const PAIRTYPE(void*, CLockLocation)& i, s1)
62 if (i.first == mismatch.first) printf(" (1)");
63 if (i.first == mismatch.second) printf(" (2)");
64 printf(" %s\n", i.second.ToString().c_str());
68 static void push_lock(void* c, const CLockLocation& locklocation, bool fTry)
70 if (lockstack.get() == NULL)
71 lockstack.reset(new LockStack);
73 if (fDebug) printf("Locking: %s\n", locklocation.ToString().c_str());
76 (*lockstack).push_back(std::make_pair(c, locklocation));
79 BOOST_FOREACH(const PAIRTYPE(void*, CLockLocation)& i, (*lockstack)) {
80 if (i.first == c) break;
82 std::pair<void*, void*> p1 = std::make_pair(i.first, c);
83 if (lockorders.count(p1))
85 lockorders[p1] = (*lockstack);
87 std::pair<void*, void*> p2 = std::make_pair(c, i.first);
88 if (lockorders.count(p2))
90 potential_deadlock_detected(p1, lockorders[p2], lockorders[p1]);
98 static void pop_lock()
102 const CLockLocation& locklocation = (*lockstack).rbegin()->second;
103 printf("Unlocked: %s\n", locklocation.ToString().c_str());
106 (*lockstack).pop_back();
110 void EnterCritical(const char* pszName, const char* pszFile, int nLine, void* cs, bool fTry)
112 push_lock(cs, CLockLocation(pszName, pszFile, nLine), fTry);
120 #endif /* DEBUG_LOCKORDER */