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 #ifdef DEBUG_LOCKCONTENTION
9 void PrintLockContention(const char* pszName, const char* pszFile, int nLine)
11 printf("LOCKCONTENTION: %s\n", pszName);
12 printf("Locker: %s:%d\n", pszFile, nLine);
14 #endif /* DEBUG_LOCKCONTENTION */
16 #ifdef DEBUG_LOCKORDER
18 // Early deadlock detection.
19 // Problem being solved:
20 // Thread 1 locks A, then B, then C
21 // Thread 2 locks D, then C, then A
22 // --> may result in deadlock between the two threads, depending on when they run.
23 // Solution implemented here:
24 // Keep track of pairs of locks: (A before B), (A before C), etc.
25 // Complain if any thread tries to lock in a different order.
30 CLockLocation(const char* pszName, const char* pszFile, int nLine)
37 std::string ToString() const
39 return mutexName+" "+sourceFile+":"+std::to_string(sourceLine);
43 std::string mutexName;
44 std::string sourceFile;
48 typedef std::vector< std::pair<void*, CLockLocation> > LockStack;
50 static boost::mutex dd_mutex;
51 static std::map<std::pair<void*, void*>, LockStack> lockorders;
52 static boost::thread_specific_ptr<LockStack> lockstack;
55 static void potential_deadlock_detected(const std::pair<void*, void*>& mismatch, const LockStack& s1, const LockStack& s2)
57 printf("POTENTIAL DEADLOCK DETECTED\n");
58 printf("Previous lock order was:\n");
59 for(const auto& i, s2)
61 if (i.first == mismatch.first) printf(" (1)");
62 if (i.first == mismatch.second) printf(" (2)");
63 printf(" %s\n", i.second.ToString().c_str());
65 printf("Current lock order is:\n");
66 for(const auto& i, s1)
68 if (i.first == mismatch.first) printf(" (1)");
69 if (i.first == mismatch.second) printf(" (2)");
70 printf(" %s\n", i.second.ToString().c_str());
74 static void push_lock(void* c, const CLockLocation& locklocation, bool fTry)
76 if (lockstack.get() == NULL)
77 lockstack.reset(new LockStack);
79 if (fDebug) printf("Locking: %s\n", locklocation.ToString().c_str());
82 (*lockstack).push_back(std::make_pair(c, locklocation));
85 for(const auto& i : (*lockstack)) {
86 if (i.first == c) break;
88 std::pair<void*, void*> p1 = std::make_pair(i.first, c);
89 if (lockorders.count(p1))
91 lockorders[p1] = (*lockstack);
93 std::pair<void*, void*> p2 = std::make_pair(c, i.first);
94 if (lockorders.count(p2))
96 potential_deadlock_detected(p1, lockorders[p2], lockorders[p1]);
104 static void pop_lock()
108 const CLockLocation& locklocation = (*lockstack).rbegin()->second;
109 printf("Unlocked: %s\n", locklocation.ToString().c_str());
112 (*lockstack).pop_back();
116 void EnterCritical(const char* pszName, const char* pszFile, int nLine, void* cs, bool fTry)
118 push_lock(cs, CLockLocation(pszName, pszFile, nLine), fTry);
126 #endif /* DEBUG_LOCKORDER */