Implementing a FIFO mutex in pthreads

前端 未结 6 1956
失恋的感觉
失恋的感觉 2020-12-03 05:33

I\'m trying to implement a binary tree supporting concurrent insertions (which could occur even between nodes), but without having to allocate a global lock or a separate mu

6条回答
  •  不知归路
    2020-12-03 06:09

    You could do something like this:

    • define a "queued lock" that consists of a free/busy flag plus a linked-list of pthread condition variables. access to the queued_lock is protected by a mutex

    • to lock the queued_lock:

      • seize the mutex
      • check the 'busy' flag
      • if not busy; set busy = true; release mutex; done
      • if busy; create a new condition @ end of queue & wait on it (releasing mutex)
    • to unlock:

      • seize the mutex
      • if no other thread is queued, busy = false; release mutex; done
      • pthread_cond_signal the first waiting condition
      • do not clear the 'busy' flag - ownership is passing to the other thread
      • release mutex
    • when waiting thread unblocked by pthread_cond_signal:

      • remove our condition var from head of queue
      • release mutex

    Note that the mutex is locked only while the state of the queued_lock is being altered, not for the whole duration that the queued_lock is held.

提交回复
热议问题