How does semaphore work?

后端 未结 6 1390
粉色の甜心
粉色の甜心 2021-02-04 07:44

Can the semaphore be lower than 0? I mean, say I have a semaphore with N=3 and I call \"down\" 4 times, then N will remain 0 but one process will be blocked?

And same th

6条回答
  •  南方客
    南方客 (楼主)
    2021-02-04 08:21

    Hi Greg consider following example :

    public static void main(String [] args) throws InterruptedException {
    
            Semaphore available = new Semaphore(1, true);
    
            available.acquire();
            System.out.println("Acquire : " +available.availablePermits());
    
            available.release();
            System.out.println("Released : " +available.availablePermits());
    
            available.release();
            System.out.println("Released : " +available.availablePermits());
    
            available.release();
            System.out.println("Released : " +available.availablePermits());
    
            available.release();
            System.out.println("Released : " +available.availablePermits());
    
            available.acquire();
            System.out.println("Acquire : " +available.availablePermits());
    
            available.acquire();
            System.out.println("Acquire : " +available.availablePermits());
    
            available.acquire();
            System.out.println("Acquire : " +available.availablePermits());
    
            available.acquire();
            System.out.println("Acquire : " +available.availablePermits());
    
            available.acquire();
            System.out.println("Acquire : " +available.availablePermits());
        }
    

    If you see the output u will get following :

    Acquire : 0
    Released : 1
    Released : 2
    Released : 3
    Released : 4
    Acquire : 3
    Acquire : 2
    Acquire : 1
    Acquire : 0
    

    And wait is going on.

    So basically permit will increase on every release and acquire will decrease it until 0. Once it reached 0 it will wait until release is called on same object :)

提交回复
热议问题