Avoid deadlock in a single thread

Viewed 635

I have the following problem: I have a class that needs to be protected from simultaneous access from different threads. The class has two methods: lock() and unlock() using (g_mutex_lock / g_mutex_unlock with a per-object GMutex). Now a locking method looks like this:

void Object::method()
{
    lock();
    // do stuff modifying the object
    unlock();
}

Now lets assume that I have two mwthods of this type, method1() and method2() which I call one after another:

object.method1();
// but what if some other thread modifies object in between
object.method2();

I tried locking the object before this block und unlocking it again, but in this case there is a deadlock even with a single thread because the GMutex doesn't know that it has already been locked by the same thread. A solution would be to modify the method to accept an additional bool to determine whether the object is already locked. But is there a more elegant concept? Or is this a shortcoming regarding the design concept in total?

3 Answers
Related