Semaphore mechanism to achieve mutual exclusion process
1. Analyze the critical activities of concurrent processes and define critical areas
2. Set the mutex property. The initial value is 1
3. Execute P (MUtex) before critical section
4. Execute V (MUtex) after critical section
semaphore mutex = 1; // initialize the semaphore P1(){... P(mutex); // Use the critical resource to lock the critical section code segment... V(mutex); // Use critical resources to unlock... } P2(){ ... P(mutex); // Use the critical resource to lock the critical section code segment... V(mutex); // Use critical resources to unlock... }Copy the code
Two. Semaphore mechanism to achieve synchronization
1. Analyze where a “synchronization relationship” needs to be implemented, that is, two operations (or lines of code) that are guaranteed to be performed by “one before and one after”
2. Set synchronization semaphore S. The initial value is 0
3. Execute V(S) after “Front Action”
4. Execute P(S) before “after Action”
semaphore S = 0; P1 () {code 1; Code 2; V(S); Code 3; } P2(){ P(S); Code 4; Code 5; Code 6; }Copy the code
If V(S) is performed first, S=1 after S++. Later, when P(S) is executed, S– is executed since S = 1, indicating that there is a resource available, and the value of S changes back to 0. Instead of executing the block primitive, P2 continues to execute code 4.
If the P(S) operation is performed first, S=0 and S– after S=-1 indicates that there are no available resources at this time. Therefore, block primitives are executed during the P operation to actively request blocking. Then, after code 2 is executed, V(S), S++, is executed to make S return to 0, since there is a process in the blocking queue corresponding to the semaphore
Producer-consumer issues
The system has a set of producer processes and a set of consumer processes. The producer processes produce one product at a time into the buffer, and the consumer Jin Heng takes one product at a time out of the buffer and uses it. Producers and consumers share an initially empty buffer of size N.
Producers can only put their products into the buffer if the buffer is not full, otherwise they must wait. (Synchronization relationship)
Only when the buffer is not empty can the consumer take the product out of it, otherwise he must wait. (Synchronization relationship)
Buffers are critical resources and must be mutually exclusive for each process. (Mutually exclusive)
semaphore mutex = 1; Sempaphore empty = n; Sempaphore full = 0; // Producer (){while(1){producer(){producer(); P(empty); P(mutex); Put the product in the buffer; V(mutex); V(full); } } consumer(){ while(1){ P(full); P(mutex); Fetching a product from the buffer; V(mutex); V(empty); }}Copy the code
Question: Can I change the order of adjacent P and V operations?
You cannot change the order of P operations because a deadlock occurs when empty = 0 and full = n.
You can change the order in which V operates.