Linux 与 FIFO 等待队列同步 [英] Linux synchronization with FIFO waiting queue

查看:33
本文介绍了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);
}

这篇关于Linux 与 FIFO 等待队列同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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