Game Development Community

Threading, Mutexes, and Deadlock....

by Dallin Wellington · in Technical Issues · 06/24/2008 (10:55 pm) · 2 replies

What is the best way to avoid deadlock 100% in a program, but use the least amount of mutexes as possible. Im getting very frustrated with threading because i dont wanna use locks, but i need to or it will screw up certain things, but i want to avoid deadlock 100%.

#1
06/24/2008 (11:11 pm)
Quote:What is the best way to avoid deadlock 100% in a program

Always always always always always lock mutexes in the same order. eg, if you have two mutexes A and B, and two objects that need both, X and Y, then your code has to look like this in both X and Y:

lock_mutex(A);
lock_mutex(B);

never ever ever lock mutex B before mutex A. There is no "what if" clause here.

Also keep your critical sections ["the amount of time you have a mutex locked for"] as short as possible, but that on its own cannot stop deadlock, it just stops your program from ever blocking for very long.

You'll also see what looks like a deadlock if you forget to unlock a mutex, but that's not actually a deadlock, that's just a normal lockup :-)
I don't know if torque has a mutexlocker type object, but it's common to see something like a mutexlocker object that you pass a mutex to, that locks that mutex when it's constructed and unlocks the mutex when it's destroyed. eg:

class foo {
public:
  void do_something() {
    MutexLocker ml(a);
    do_stuff_that_required_that_lock;
    // No need to do anything here, ml is deleted when
    //   it leaves scope which automatically unlocks the mutex
  }
protected:
  Mutex a;
};

Quote:but use the least amount of mutexes as possible

This is a design question and entirely separate from the "always lock them in the same order" above. You just gotta change your code around.

Gary (-;
#2
06/24/2008 (11:55 pm)
Is it possible to use a mutex on the -> and . operators? Therefore making every object Thread Safe that inherits the object with the overloaded operators, and invulnerable to deadlock?