简体   繁体   English

我们是否可以为所有其他调用使用pthreads互斥锁来锁定函数?

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

Say a program spawns a thread. 说一个程序产生一个线程。 That thread calls func1(). 该线程调用func1()。 However, func1() is also called in various places elsewhere in the main app. 但是,func1()在主应用程序的其他位置也被调用。 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? 而且,如果它在其中调用了其他函数,而且还在各个地方的主应用程序上调用了这些函数,是否必须递归地锁定它们?

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() ). 例如,如果func1()func2()都访问共享变量x ,并且您可以从func1()main()调用func2() main() ,则您将不得不设计一个解决方案来检测是否互斥锁已被锁定,因此func2()可以声明/释放(从main调用时)或什么都不做(从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; 只要声明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). 好的设计是锁定数据,而不要具有全局变量(或单例变量,这是对全局变量的委婉说法)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM