Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/ssh/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Multithreading 单车道桥梁问题的解决方案怎么不是无饥饿的?_Multithreading_Deadlock_Semaphore_Mutual Exclusion_Starvation - Fatal编程技术网

Multithreading 单车道桥梁问题的解决方案怎么不是无饥饿的?

Multithreading 单车道桥梁问题的解决方案怎么不是无饥饿的?,multithreading,deadlock,semaphore,mutual-exclusion,starvation,Multithreading,Deadlock,Semaphore,Mutual Exclusion,Starvation,我这里有一个单车道桥梁问题的解决方案。我想知道这个解决方案怎么不是无饥饿的 问题是,来自北方和南方的汽车到达一座单线桥。朝同一方向行驶的车辆可以同时通过桥梁,但朝相反方向行驶的车辆不能 public class Bridge { static int N = 5 ; //# of cars coming in at the same time static int nN = 0; // # of northbound cars on bridge static int

我这里有一个单车道桥梁问题的解决方案。我想知道这个解决方案怎么不是无饥饿的

问题是,来自北方和南方的汽车到达一座单线桥。朝同一方向行驶的车辆可以同时通过桥梁,但朝相反方向行驶的车辆不能

public class Bridge {
    static int N = 5 ; //# of cars coming in at the same time 
    static int nN = 0; // # of northbound cars on bridge
    static int nS = 0; // # of southbound cars on bridge
    static Semaphore e = new Semaphore(1); //  entry to cs
    static Semaphore n = new Semaphore(1); // delay for northbound cars
    static Semaphore s = new Semaphore(1); // delay for southbound cars
}
 public void Northbound() {
        do {
            P(Bridge.n);
                Bridge.nN++;
                if(Bridge.nN ==1) {
                    P(Bridge.e);
                }
            V(Bridge.n);
            write(i,"northbound crossing");
            P(Bridge.n);
                Bridge.nN--;
                if(Bridge.nN ==0) {
                    V(Bridge.e);
                }
            V(Bridge.n);

            try{ sleep(1000) ; } catch (InterruptedException e) { } ;
        } while (true) ;

    }
public void Southbound() {
        do {
            P(Bridge.s);
            Bridge.nS++;
            if(Bridge.nS ==1) {
                P(Bridge.e);
            }
        V(Bridge.s);
        read(i,"northbound crossing");
        P(Bridge.s);
            Bridge.nS--;
            if(Bridge.nS ==0) {
                V(Bridge.e);
            }
        V(Bridge.s);
            try{ sleep(1000) ; } catch (InterruptedException e) { } ;

         } while (true) ;
    }
void P(Semaphore s) {
        try {
            s.acquire();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    //increment semaphore
    void V(Semaphore s) {
        s.release();
    }