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.
9 #ifdef DEBUG_LOCKCONTENTION
10 void PrintLockContention(const char* pszName, const char* pszFile, int nLine)
12 printf("LOCKCONTENTION: %s\n", pszName);
13 printf("Locker: %s:%d\n", pszFile, nLine);
15 #endif /* DEBUG_LOCKCONTENTION */
17 #ifdef DEBUG_LOCKORDER
19 // Early deadlock detection.
20 // Problem being solved:
21 // Thread 1 locks A, then B, then C
22 // Thread 2 locks D, then C, then A
23 // --> may result in deadlock between the two threads, depending on when they run.
24 // Solution implemented here:
25 // Keep track of pairs of locks: (A before B), (A before C), etc.
26 // Complain if any thread tries to lock in a different order.
31 CLockLocation(const char* pszName, const char* pszFile, int nLine)
38 std::string ToString() const
40 return mutexName+" "+sourceFile+":"+itostr(sourceLine);
44 std::string mutexName;
45 std::string sourceFile;
49 typedef std::vector< std::pair<void*, CLockLocation> > LockStack;
51 static boost::mutex dd_mutex;
52 static std::map<std::pair<void*, void*>, LockStack> lockorders;
53 static boost::thread_specific_ptr<LockStack> lockstack;
56 static void potential_deadlock_detected(const std::pair<void*, void*>& mismatch, const LockStack& s1, const LockStack& s2)
58 printf("POTENTIAL DEADLOCK DETECTED\n");
59 printf("Previous lock order was:\n");
60 for (const auto& i : s2)
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());
66 printf("Current lock order is:\n");
67 for (const auto& i : s1)
69 if (i.first == mismatch.first) printf(" (1)");
70 if (i.first == mismatch.second) printf(" (2)");
71 printf(" %s\n", i.second.ToString().c_str());
75 static void push_lock(void* c, const CLockLocation& locklocation, bool fTry)
77 if (lockstack.get() == NULL)
78 lockstack.reset(new LockStack);
80 if (fDebug) printf("Locking: %s\n", locklocation.ToString().c_str());
83 (*lockstack).push_back(std::make_pair(c, locklocation));
86 for (const auto& i : (*lockstack)) {
87 if (i.first == c) break;
89 std::pair<void*, void*> p1 = std::make_pair(i.first, c);
90 if (lockorders.count(p1))
92 lockorders[p1] = (*lockstack);
94 std::pair<void*, void*> p2 = std::make_pair(c, i.first);
95 if (lockorders.count(p2))
97 potential_deadlock_detected(p1, lockorders[p2], lockorders[p1]);
105 static void pop_lock()
109 const CLockLocation& locklocation = (*lockstack).rbegin()->second;
110 printf("Unlocked: %s\n", locklocation.ToString().c_str());
113 (*lockstack).pop_back();
117 void EnterCritical(const char* pszName, const char* pszFile, int nLine, void* cs, bool fTry)
119 push_lock(cs, CLockLocation(pszName, pszFile, nLine), fTry);
127 #endif /* DEBUG_LOCKORDER */