How does semaphore work?

后端 未结 6 1386
粉色の甜心
粉色の甜心 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:26

    Using java.util.concurrent.Semaphore with methods acquire() and release(), I think permits will always be >=0. Let's say you want to synchronize threads so that only 1 thread can be inside for loop. If sem is type of Semaphore that has initial value 1, this will not work for more than 2 threads.

    while(true){            
    
        sem.wait(); // wait is acquire
    
        for(int i=0; i<=5; i++){
    
            try {
                Thread.sleep(250);
            }catch (InterruptedException e) {}
    
            System.out.println("Thread "+ threadname+ " " + i);
    
                 }
        sem.signal(); // signal is release }
    

    However, you can implement the Semaphore class from java and make your own class that allows this.

    package yourpackage;
    
    import java.util.concurrent.Semaphore;
    
    public class SemaphoreLayer {
    public Semaphore s=null;
    public String name;
    private int val;
    
    public SemaphoreLayer(int i){
        s=new Semaphore(i); val=i;
    }
    
    public void wait(){
     try {
         val--;
         s.acquire();
    
      } catch (InterruptedException e) {
        System.out.println("Error signal semaphorelayer");
    }}
    
    public void signal(){
        if(val<0){val++;}{
            s.release();
            val++;
        }
    }
    
    }
    

    Now val can be negative. However, I am not sure that this is completely safe, because if we have signal from one thread and wait from the other and they try val++ and val-- this can be bad. (chances for this are very small but stil they exist, so if you are coding and you have to be 100% no error, I don't recommend using this code ) In conclusion this is why it is better to use concept of monitors in java and key word synchronized.

提交回复
热议问题