pthreads mutex vs semaphore

后端 未结 9 1096
旧巷少年郎
旧巷少年郎 2020-12-12 11:31

What is the difference between semaphores and mutex provided by pthread library ?

9条回答
  •  失恋的感觉
    2020-12-12 11:50

    Mutex is like sempaphore with with S=1.

    You can control number of concurrent accesses with semaphore but with mutex only one process at a time can access it.

    See the implemenation of these two below: (all functions are atomic)

    Semaphore:

    wait(S) {
          while (S <= 0 )
             ; // busy wait
          S--;
    }
    
    signal(S) {
          S++;
    }
    

    Mutex:

    acquire() {
          while (!available)
                ; // busy wait
          available = false;
    }
    
    release() {
          available = true;
    }
    

提交回复
热议问题