Linux synchronization with FIFO waiting queue

后端 未结 3 860
别跟我提以往
别跟我提以往 2020-12-15 02:01

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

3条回答
  •  孤街浪徒
    2020-12-15 02:07

    Here is a way to create a simple queueing "ticket lock", built on pthreads primitives. It should give you some ideas:

    #include 
    
    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);
    }
    

提交回复
热议问题