如何使用 POSIX 线程声明递归互斥体?
我对如何使用 pthread 声明递归互斥体有点困惑。 我尝试做的是一次只有一个线程能够运行一段代码(包括函数),但在怀疑之后我发现使用互斥体不起作用,而我应该使用递归互斥体。这是我的代码:
pthread_mutex_lock(&mutex); // LOCK
item = queue_peek(queue); // get last item in queue
item_buff=item; // save item to a buffer
queue_removelast(queue); // remove last item from queue
pthread_mutex_unlock(&mutex); // UNLOCK
所以我尝试做的只是从队列中串行读取/删除。
问题是没有任何关于如何声明递归互斥体的示例。或者可能有一些,但它们不适合我编译。
I am a bit confused on how to declare a recursive mutex using pthread.
What I try to do is have only one thread at a time be able to run a piece of code(including functions) but after scepticism I figured out that the use of mutexes would not work and that instead I should use recursive mutexes. Here is my code:
pthread_mutex_lock(&mutex); // LOCK
item = queue_peek(queue); // get last item in queue
item_buff=item; // save item to a buffer
queue_removelast(queue); // remove last item from queue
pthread_mutex_unlock(&mutex); // UNLOCK
So what I try to do is just read/remove from the queue serially.
The thing is that there isn't any example out there on how to declare recursive mutexes. Or there maybe a few but they don't compile for me.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Michael Foukarakis 的代码几乎不错,但他初始化了互斥体两次,这导致了未定义的行为。它应该是:
我实际上在生产中使用了这段代码,并且我知道它可以在 Linux、Solaris、HP-UX、AIX、Mac OSX 和 FreeBSD 上正常工作。
您还需要添加适当的链接器标志来编译它:
The code from Michael Foukarakis is almost good but he initializes the mutex twice which leads to undefined behavior. It should just be:
I actually use this code in production, and I know it works correctly on Linux, Solaris, HP-UX, AIX, Mac OSX and FreeBSD.
You also need to add proper linker flag to compile this:
要创建递归互斥体,您可以使用:
其中 type 为 PTHREAD_MUTEX_RECURSIVE 或初始化程序。
例如:
或者,在运行时初始化(不要同时进行,这是未定义的行为):
To create a recursive mutex, you can either use:
where type is
PTHREAD_MUTEX_RECURSIVE
, or an initialiser.For example:
or alternatively, initialize at runtime (don't do both, it's undefined behaviour):
在 Linux 上(但这不能移植到其他系统),如果互斥体是全局变量或静态变量,您可以像这样初始化它
(顺便说一句,示例来自
pthread_mutex_init(3)
< em>手册页!)On Linux (but this is non portable to other systems), if the mutex is a global or static variable, you could initialize it like
(and by the way, the example is from
pthread_mutex_init(3)
man pages!)创建互斥体时需要添加互斥体属性。
调用
pthread_mutexattr_init
,然后使用PTHREAD_MUTEX_RECURSIVE
调用pthread_mutexattr_settype
,然后通过pthread_mutex_init
使用这些属性。阅读 man pthread_mutexattr_init 来了解更多信息。You need to add mutex attributes when creating the mutex.
Call
pthread_mutexattr_init
, thenpthread_mutexattr_settype
withPTHREAD_MUTEX_RECURSIVE
then use these attributes withpthread_mutex_init
. Readman pthread_mutexattr_init
for more info.