Implementing semaphore by using mutex operations and primitives

前端 未结 4 1004
后悔当初
后悔当初 2021-02-09 18:27

Some time ago had an interview and was asked to implement Semaphore by using mutex operations and primitives only (he allowed int to be considered as atomic). I came with soluti

4条回答
  •  闹比i
    闹比i (楼主)
    2021-02-09 19:03

    lemme try this

    `

    # number of threads/workers
    w = 10
    # maximum concurrency
    cr = 5
    r_mutex = mutex()
    w_mutex = [mutex() for x in range(w)]
    
    # assuming mutex can be locked and unlocked by anyone 
    # (essentially we need a binary semaphore)
    
    def acquire(id):
    
        r_mutex.lock()
        cr -= 1
        # r_mutex.unlock()
        
        # if exceeding maximum concurrency
        if cr < 0:
            # lock twice to be waken up by someone
            w_mutex[id].lock()
            r_mutex.unlock()
            w_mutex[id].lock()
            w_mutex[id].unlock()
            return
    
        r_mutex.unlock()
    
        
        
           
    def release(id):
    
        r_mutex.lock()
        cr += 1
        # someone must be waiting if cr < 0
        if cr <= 0:
            # maybe you can do this in a random order
            for w in w_mutex:
                if w.is_locked():
                    w.unlock()
                    break
        r_mutex.unlock()
    

    `

提交回复
热议问题