Implementing semaphore by using mutex operations and primitives

前端 未结 4 1014
后悔当初
后悔当初 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条回答
  •  星月不相逢
    2021-02-09 18:57

    EDIT - use a second mutex for queuing intstead of threads

    Since a mutex already have proper thread-support, it can be used to queue the threads (instead of doing it explicitly as I first had tried to do). Unless the mutex is restricted to only let the owner unlock it (a lock?), then this solution doesn't work.

    I found the solution in Anthony Howe's pdf that I came across when searching. There are two more solutions given there as well. I changed the names to make more sense for this example.

    more or less pseudo code:

    Semaphore{
        int n;
        mutex* m_count;         //unlocked initially
        mutex* m_queue;         //locked initially
    };
    
    void wait(){
        m_count.lock();
        n = n-1;
        if(n < 0){
            m_count.unlock();
            m_queue.lock();     //wait
        }
        m_count.unlock();       //unlock signal's lock
    }
    
    void signal(){
        m_count.lock();
        n = n+1;
    
        if(n <= 0){
            m_queue.unlock();   //leave m_count locked
        }
        else{
            m_count.unlock();
        }
    }
    

提交回复
热议问题