OS_PV operation_1. Warehouse problem

Warehouse problem

There is a warehouse that can store both products A and B. The storage space of the warehouse is large enough, but the requirements are: (1) Only one product (A or B) can be stored at a time; (2)-N <(A product quantity -B product quantity) <M. Among them, N and M are positive integers. Try out "Storage A" and "Storage B" and P and V operations to describe the warehousing process of product A and product B.

Semaphore Sa = M - 1;
Semaphore Sb = N - 1;
//代表还能存入的数量

Semaphore mutex = 1;

process_A() {
    
    
	while(1){
    
    
		P(Sa); //取一个A产品准备入库
		P(mutex);
		A产品入库;
		// A产品入库后还能存入A产品数量-1
		V(mutex);
		V(Sb); //还能存入B产品数量+1
	}
}

process_B() {
    
    
	while(1){
    
    
		P(Sb); //取一个B产品准备入库
		P(mutex);
		B产品入库;
		// B产品入库后还能存入B产品数量-1
		V(mutex);
		V(Sa); //还能存入A产品数量+1
	}
}

Guess you like

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