For the next few paragraphs, you'll be one of the people who write games. Congratulations, you can play at work!
You're developing a server and you have to write code for exchanging loot between two users:
class user { boost::mutex loot_mutex_; std::vector<item_t> loot_; public: // ... void exchange_loot(user& u); };
Each user action could be concurrently processed by different threads on a server, so you have to guard the resources by mutexes. The junior developer tried to deal with the problem, but his solution does not work:
void user::exchange_loot(user& u) { // Terribly wrong!!! ABBA deadlocks. boost::lock_guard<boost::mutex> l0(loot_mutex_); boost::lock_guard<boost::mutex> l1(u.loot_mutex_); loot_.swap(u.loot_); }
The issue in the preceding code is a well-known ABBA deadlock problem. Imagine that thread 1 locks mutex A and thread 2 locks mutex B. And now thread 1 attempts to lock the already locked...