OS_PV operation_4. Crossing the single-plank bridge problem

The problem of crossing a single-plank bridge

A certain river has only one single-plank bridge (east-west) for pedestrians to cross the river. There are people on both sides of the river who want to cross the bridge. Follow the rules below to cross the bridge. In order to ensure the safety of crossing the bridge, please use the P and V operations to achieve correct management.
rule:

  1. People in the same direction can cross the bridge continuously, but the number of people who can cross the bridge continuously is up to 10 people.
  2. When someone crosses the bridge in one direction, people in the other direction have to wait

My understanding of this topic: When people in one direction start to cross the bridge, there are at most 10 people on the bridge. If the bridge is full, then people in the same direction must wait until people in this direction want to cross the bridge. All cross the bridge, and the opposing talent can cross the bridge. ( The code below is coded according to this understanding )

The second understanding (a bit contradictory): Cross the bridge alternately in east and west directions, up to ten consecutive bridges at a time. I was thinking, assuming that there are 25 people crossing the bridge in the east direction and 10 people crossing the bridge in the west direction, when 10 people have passed in the east direction (15 remaining), then 10 people in the west direction will cross the bridge (0 remaining) ), and then 10 more in the east direction (5 remaining). At this time, because there are people crossing the bridge in the west direction, but no one is crossing the bridge in the west direction, if no one crosses the bridge in the west direction, do I have to wait for the east direction? Very contradictory. So I designed it according to the first understanding. (If you follow this understanding, you need to add a little precondition: assuming there are infinite people on both sides)

Semaphore bridge = 10; //桥互斥信号量
Semaphore wait = 1;   //等待互斥, 当对面方向有人过桥就等待
Semaphore mutex1 = 1; //东方向互斥信号量
Semaphore mutex2 = 1; //西方向互斥信号量

int count1 = 0;		  //东方向要过桥人数, 要过桥+1, 已经过桥-1
int count2 = 0;       //西方向要过桥人数, 要过桥+1, 已经过桥-1

process_1{
    
    
	P(mutex1);
		if (count1 == 0) {
    
    
			P(wait);
		}
		count1++;
	V(mutex1);
	
	P(bridge);
		东方向人过桥();
	V(bridge);
	
	P(mutex1);
		count1--;
		if (count1 == 0) {
    
    
			V(wait);
		}
	V(mutex1);
}

process_2{
    
    
	P(mutex2);
		if (count2 == 0) {
    
    
			P(wait);
		}
		count2++;
	V(mutex2);
	
	P(bridge);
		西方向人过桥();
	V(bridge);
	
	P(mutex2);
		count2--;
		if (count2 == 0) {
    
    
			V(wait);
		}
	V(mutex2);
}

Guess you like

Origin blog.csdn.net/qq_39906884/article/details/109112046