Linux与FIFO等待队列的同步
问题描述:
在等待队列为FIFO的Linux中是否有锁?这似乎是一件显而易见的事情,但是我刚刚发现pthread互斥锁不是FIFO,信号量显然也不是FIFO(我正在研究内核2.4(家庭作业))...
Are there locks in Linux where the waiting queue is FIFO? This seems like such an obvious thing, and yet I just discovered that pthread mutexes aren't FIFO, and semaphores apparently aren't FIFO either (I'm working on kernel 2.4 (homework))...
Linux是否具有带有FIFO等待队列的锁,还是有一种简单的方法来利用现有机制进行锁定?
Does Linux have a lock with FIFO waiting queue, or is there an easy way to make one with existing mechanisms?
答
这里是一种创建基于pthreads原语的简单队列票证锁"的方法.它应该给您一些想法:
Here is a way to create a simple queueing "ticket lock", built on pthreads primitives. It should give you some ideas:
#include <pthread.h>
typedef struct ticket_lock {
pthread_cond_t cond;
pthread_mutex_t mutex;
unsigned long queue_head, queue_tail;
} ticket_lock_t;
#define TICKET_LOCK_INITIALIZER { PTHREAD_COND_INITIALIZER, PTHREAD_MUTEX_INITIALIZER }
void ticket_lock(ticket_lock_t *ticket)
{
unsigned long queue_me;
pthread_mutex_lock(&ticket->mutex);
queue_me = ticket->queue_tail++;
while (queue_me != ticket->queue_head)
{
pthread_cond_wait(&ticket->cond, &ticket->mutex);
}
pthread_mutex_unlock(&ticket->mutex);
}
void ticket_unlock(ticket_lock_t *ticket)
{
pthread_mutex_lock(&ticket->mutex);
ticket->queue_head++;
pthread_cond_broadcast(&ticket->cond);
pthread_mutex_unlock(&ticket->mutex);
}