Question

I've been playing around with gtkmm and multi-threaded GUIs and stumbled into the concept of a mutex. From what I've been able to gather, it serves the purpose of locking access to a variable for a single thread in order to avoid concurrency issues. This I understand, seems rather natural, however I still don't get how and when one should use a mutex. I've seen several uses where the mutex is only locked to access particular variables (e.g.like this tutorial). For which type of variables/data should a mutex be used?

PS: Most of the answers I've found on this subject are rather technical, and since I am far from an expert on this I was looking more for a conceptual answer.

Was it helpful?

Solution

If you have data that is accessed from more than a single thread, you probably need a mutex. You usually see something like

theMutex.lock()
do_something_with_data()
theMutex.unlock()

or a better idiom in c++ would be:

{
    MutexGuard m(theMutex)
    do_something_with_data()
}

where MutexGuard c'tor does the lock() and d'tor does the unlock()

This general rule has a few exceptions

  • if the data you are using can be accessed in an atomic manner, you don't need a lock. In Visual Studio you have functions like InterlockedIncrement() that do this. gcc has it's own facilities to do this.

  • If you are accessing the data to only ever read it and never change it, it's usually safe to do without locking. but if even a single thread does any change to the data, all the other threads need to make sure they don't try to read the data while it is being changed. You can also read about Reader-Writer lock for this kind of situations.

OTHER TIPS

variables that are changed among multiple threads. So data that is not modified (immutable) or data that is not shared does not need

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top