pthreads: thread starvation caused by quick re-locking

前端 未结 5 601
误落风尘
误落风尘 2020-11-28 13:01

I have a two threads, one which works in a tight loop, and the other which occasionally needs to perform a synchronization with the first:

// thread 1
while(         


        
5条回答
  •  隐瞒了意图╮
    2020-11-28 13:22

    You can build a FIFO "ticket lock" on top of pthreads mutexes, along these lines:

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

    Under this kind of scheme, no low-level pthreads mutex is held while a thread is within the ticketlock protected critical section, allowing other threads to join the queue.

提交回复
热议问题