Say a program spawns a thread. That thread calls func1(). However, func1() is also called in various places elsewhere in the main app. If i wrap it in a mutex lock in the thread only, will it be safe for the whole of the app? Or will one have to go in it and lock it? And if in it are other functions that are called by it but also on the main app in various places, does one have to go recursively and lock them?
Say a program spawns a thread. That thread calls func1(). However, func1() is also
Share
Get out of the habit of thinking that you protect functions with mutexes, you don’t.
You actually protect resources such as variables shared amongst threads.
Once you accept that little pearl of wisdom, you start thinking in terms of what data has to be protected and can minimise the granularity of the protections.
For example, if
func1()andfunc2()both access the shared variablex, and you can callfunc2()either fromfunc1()ormain(), you’re going to have to engineer a solution that can detect if the mutex is already locked so thatfunc2()can claim/release (when called frommain) or do nothing (when called fromfunc1()). Either that or use a recursive mutex.Functions which are thread-unsafe (such as using static data areas) can be protected with mutexes but I find it’s usually easier to refactor them so that they’re inherently thread-safe (with allocated memory or thread-local storage).