OS_PV operation_5. Pedestrian and motor vehicle crossing problem

Pedestrian and motor vehicle crossing problem

Assuming that there is an intersection, the traffic rules are as follows: as long as there is no motor vehicle passing through the intersection, pedestrians can pass; only when no pedestrians are passing through the intersection and no other vehicles are passing through the intersection, the motor vehicle can pass. Please use P and V operations to describe the synchronization and mutual exclusion process of pedestrians and motor vehicles passing through the intersection.

My understanding: the priority of pedestrians crossing the intersection is greater than the priority of motor vehicles crossing the intersection; each time a vehicle or person passes through the intersection. When there is no one, the motor vehicles pass in turn; when there are people, the cars must wait for all people to pass through the intersection before they can pass.

int count = 0;          // 记录行人数量
Semaphore mutex = 1;    // 保护count更新
Semaphore crossing = 1; // 互斥路口使用
//Semaphore pass = 1;     // 保证过路人优先级

process_car() {
    
    
	while(true) {
    
    
		P(crossing);
			机动车通过路口();
		V(crossing);
	}
}

process_passenger() {
    
    
	while(true) {
    
    
		P(mutex);
			if(count == 0) {
    
    
				P(crossing);
			}
			count++;
		V(mutex);
		
		行人通过路口();
		
		P(mutex);
			count--;
			if(count == 0) {
    
    
				V(crossing);
			}
		V(mutex);
	}
}

Guess you like

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