C:你如何申报使用POSIX线程递归互斥? [英] C: How do you declare a recursive mutex with POSIX threads?

查看:189
本文介绍了C:你如何申报使用POSIX线程递归互斥?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何使用声明的pthread递归互斥有点糊涂了。
我尝试做的是只有一个线程在同一时间内能够运行一段code(包括功能),但持怀疑态度之​​后,我想通了,使用互斥锁是行不通的,而且不是我应该使用递归互斥。这里是我的code:

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.

推荐答案

code迈克尔Foukarakis几乎是好的,但他两次初始化互斥导致未定义的行为。它应该只是这样的:

Code from Michael Foukarakis is almost good but he initializes mutex twice which leads to undefined behavior. It should be just like that:

pthread_mutex_t Mutex;
pthread_mutexattr_t Attr;

pthread_mutexattr_init(&Attr);
pthread_mutexattr_settype(&Attr, PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init(&Mutex, &Attr);

我实际上可以用于生产该code,我知道它正常工作在Linux,Solaris,HP-UX,AIX,Mac OSX和FreeBSD的。

I acutally uses this code in production, and I know it works correctly on Linux, Solaris, HP-UX, AIX, Mac OSX and FreeBSD.

/编辑

您还需要添加适当的链接器标志编译此。


AIX,Linux和FreeBSD的:

CPLATFORM + = -pthread



mingw32的:

LDFLAGS + = -lpthread

You also need to add proper linker flag to compile this.

AIX, Linux, FreeBSD:
CPLATFORM += -pthread

mingw32:
LDFLAGS += -lpthread

这篇关于C:你如何申报使用POSIX线程递归互斥?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆