Using semaphores to implement process mutex examples and solve the problem of dining philosophers
First, we talked about the process of communication between the process of the concept of mutual exclusion, the following write a program to simulate, the program flow chart as follows:
That is, the parent process prints the character O, child process print character x, every time after printing a character to sleep, here to demonstrate the effect is that the printing process at the boundaries of the PV operation, so that each process in the middle of sleep time even if the time slice rotation to another process, because resources are not used will not be interspersed with other characters, That is to say, O or x characters will appear in pairs, such as ooxxooooxxxxxxoo ....
The procedure is as follows:
#include <sys/types.h> #include <unistd.h> #include <errno.h> #include <sys/ipc.h> # include<sys/sem.h> #include <sys/wait.h> #define ERR_EXIT (m) \ Do {\ perror (m); \ Exi T (exit_failure); \} while (0) union semun {int val; /* Value for Setval * * struct semid_ds *buf; /* Buffer for Ipc_stat, Ipc_set * * unsigned short *array; /* Array for GETALL, SetAll * * struct seminfo *__buf;
/* Buffer for Ipc_info (linux-specific) */};
int semid;
/* PV operation of the critical section, resulting in the printed characters must be in pairs appear in the/void print (char op_char) {int pause_time;
Srand (Getpid ());
int i;
for (i = 0; i < i++) {sem_p (semid);
printf ("%c", Op_char);
Fflush (stdout);
Pause_time = rand ()% 3;
Sleep (Pause_time);
printf ("%c", Op_char);
Fflush (stdout);
Sem_v (Semid);
Pause_time = rand ()% 2;
Sleep (Pause_time);
int main (void) { Semid = Sem_create (ipc_private);
Sem_setval (Semid, 1);
pid_t pid;
PID = fork ();
if (PID = = 1) err_exit ("fork");
if (PID > 0) {print (' o ');
Wait (NULL);
Sem_d (Semid);
else {print (' x ');
return 0; }
Sem_create, such as function Reference toolset. The key = Ipc_private is specified when calling Semget, which means that a private set of signals is created, but a relational process is visible, such as a parent-child process. The output is as follows:
simba@ubuntu:~/documents/code/linux_programming/unp/system_v$./print
Ooxxooxxooxxooxxooooooxxooxxooxxooxxxxxx
You can see that the output is a pair of characters that appear in pairs.
Analysis: Semval = 1, assuming that the parent process is scheduled to execute first, the parent process first p, at this time Semval = 0, the child process in the parent process when the sleep time is scheduled to try P,semval =-1, and then the child process blocked, the parent process to print out V, semval = 0, Wake up the subprocess, the p operation of the subprocess returns, the print character sleeps after V, semval = 1. Of course, the parent process may also try p when the subprocess sleeps, so it goes on and on.