Http://blog.csdn.net/raykid13/archive/2008/10/16/3087858.aspx
The semaphore structure is expressed in C as follows:
- TypedefStruct{
- IntValue;// Records the semaphore Value
- StructProcess * List;// Store the process waiting for this semaphore
- } Semaphore;
Wait () semaphoresCodeAs follows:
- Wait (semaphore * s ){
- S-> value --;
- If(S-> value <0 ){
- AddThisProcess to s-> list;
- Block ();
- }
- }
Part of the signal () semaphore code is as follows:
- Signal (semaphore * s ){
- S-> value ++;
- If(S-> value <= 0 ){
- Remove a process P from S-> list;
- Wakeup (P );
- }
- }
1. the bounded-buffer problem:
Full is initialized to 0, empty is initialized to N, and mutex is 1
-
- Do{
-
- Wait (full );
- Wait (mutex );
-
- ...
-
- // Remove an item from buffer to nextc
-
- ...
-
- Signal (mutex );
-
- Signal (empty );
-
- ...
-
- // Consume the item in nextc
-
- ...
- }While(True );
II. The readers-writers problem:
WRT Initialization is 1, readcount Initialization is 0, mutex is 1
Writer operation:
- Do{
- Wait (WRT );
- ...
- // Writing is saved med
- ...
- Signal (WRT );
- }While(True );
Reader operation:
-
- Do{
- Wait (mutex );// Ensure that operations with signal (mutex) are not interrupted by other readers
-
- Readcount ++;
-
- If(Readcount = 1)
-
- Wait (WRT );
-
- Signal (mutex );
-
- ...
-
- // Reading is already med
-
- ...
- Wait (mutex );
-
- Readcount --;
-
- If(Readcount = 0)
-
- Signal (WRT );
-
- Signal (mutex );
-
- }While(True );
III. The dining-philosophers problem:
All chopstick [5] is initialized to 1.
- Do{
-
- Wait (chopstick [I]);
-
- Wait (chopstick [(I + 1) % 5]);
-
- ...
-
- // Eating
-
- ...
-
- Signal (chopstick [I]);
-
- Signal (chopstick [(I + 1) % 5]);
-
- ...
-
- // Thinking
- ...
-
- }While(True );
But the biggest problem with this solution is its deadlock. So I think we should add a semaphore mutex and initialize it to 1:
-
- Do{
-
- Wait (mutex );
-
- Wait (chopstick [I]);
-
- Wait (chopstick [(I + 1) % 5]);
-
- Signal (mutex );
-
- ...
-
- // Eating
- ...
-
- Wait (mutex );
-
- Signal (chopstick [I]);
-
- Signal (chopstick [(I + 1) % 5]);
-
- Signal (mutex );
-
- ...
-
- // Thinking
-
- ...
-
- }While(True );
In this way, it is ensured that a philosopher cannot pick up any chopsticks during the time when he picks up two chopsticks, thus undermining the hold and wait features of the four features required for deadlock, this avoids deadlocks.
Finally, the deadlock has four features:
1. Mutual exclusion;
2. Hold and wait;
3. No preemption;
4. Circular wait;
When all four conditions are met, a deadlock may occur.