A mutex is something you grab, and will stop any other threads trying to grab it until you release it from the grabbing thread.
In your question, you have a function f allocating a Mutex instance. That is not enough to lock it. You have to specifically call mutex.lock() (in Qt, but also in general, unless you use pthread, in that case use pthread_mutex_lock and have fun with low level, platform dependent stuff. Qt abstracts it very well).
here is an example with Qt
void MyClass::doStuff( int c )
{
mutex.lock();
a = c;
b = c * 2;
mutex.unlock();
}
Once you get the lock, the call to g() will be done from the thread who got the lock, so it will be alone in that call assuming that you are not calling g() from other threads from another part of the code. Locking does not mean that it will stop all the other threads. It will stop threads trying to get the same lock, until the lock is released.
If that is the only way for your threads to reach g(), then you are synchronized on that access.
For the second part of your question, If the mutex is an instance attribute, then they will be two different mutexes. You will have to declare and instantiate a class mutex instance and refer to it foro your locking. In that case, any attempt to call a method in the class that locks the class mutex will be effectively synchronized, meaning that no two threads will execute that method together.
For example (I don't have Qt, so I cannot compile this code, and I stopped coding with it 2 years ago, so it could not work)
class Foo {
public:
void method(void) {
mutex.lock();
cout << "method called";
// long computation
mutex.unlock();
}
private:
QMutex mutex;
};
Ok, in this case, suppose you have two threads, 1 and 2, and two instances of the class Foo, a and b. Suppose that thread 1 calls a.method() and thread 2 calls b.method(). In this case, the two mutexes are different instances, so each thread will execute the call, independently, and run in parallel.
Suppose you have two threads, 1 and 2, and one instance of the class Foo which is shared between the two threads. if thread 1 calls a.method() and then thread 2 calls a.method(), thread 2 will stop and wait until the mutex lock is released.
Finally,
class Foo {
public:
void method(void) {
mutex.lock();
cout << "method called";
// long computation
mutex.unlock();
}
private:
static QMutex mutex;
};
QMutex Foo::mutex;
In this case, the mutex is a class static variable. You have only one instance of the mutex for each object instance. Suppose you had the same situation as the first case above: two threads, and two instances. In this case, when the second thread tries to call b.method() it will have to wait for a.method() to be completed by the first thread, as the lock is now unique and shared among all instances of your class.
For more info, Qt has a nice tutorial on multithreading
http://doc.trolltech.com/3.0/threads.html