开发者

Can we lock a function with a pthreads mutex for all its other calls?

开发者 https://www.devze.com 2023-01-28 18:09 出处:网络
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

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 开发者_如何学JAVAvarious places, does one have to go recursively and lock them?


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() and func2() both access the shared variable x, and you can call func2() either from func1() or main(), you're going to have to engineer a solution that can detect if the mutex is already locked so that func2() can claim/release (when called from main) or do nothing (when called from func1()). 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).


You only need to lock shared resources, or anything not thread-local. You should also consider writing your functions to be reentrant whenever possible. Reentrant functions are inherently thread-safe, whereas not all thread-safe functions can be made reentrant.


As long as you declare static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; in the function and use it, you can accomplish what you want. But making functions which are not reentrant, which have global state, etc. is generally a Bad Thing(tm). Good design is to lock data, and not to have globals (or singletons which is a euphemism for global variables).

0

精彩评论

暂无评论...
验证码 换一张
取 消