Implementing semaphore by using mutex operations and primitives

前端 未结 4 1084
后悔当初
后悔当初 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:53

    as @chill pointet out, the solution I did write down here will not work, as locks have unique ownership. I guess in the end you will revert to busy wait (if you are not allowed to use condition variables). I leave it here if ppl. have the same idea they see that this DOES NOT WORK ;)

    struct Semaphore {
    int size;
    atomic count;
    mutex protection;
    mutex wait;
    
    Semaphore(int n) : size(n) { count.store(0); }
    
    void aquire() {
        protection.lock();
        --count;
        if (count < -1) {
            protection.unlock();
            wait.lock();
        }
        protection.unlock();
    }
    
    void release() {
        protection.lock();
        ++count;
        if (count > 0) {
            wait.unlock();
        }
        protection.unlock();
    }
    };
    

提交回复
热议问题