signal Volume API synthesis Practice
Practice 1: Encapsulate the PV primitive Union mysemun{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)//};//encapsulates V operation int sem_v (int semid) {struct Sembuf buf = {0,+1,0}; Return Semop (semid,&buf,1);} Package P operation int sem_p (int semid) {struct Sembuf buf = {0,-1,0};; Return Semop (semid,&buf,1);} int main () {//create or get semaphore int semid = Semget (0x12345670,1,0666| Ipc_creat); if (Semid = =-1) {err_exit ("Semget error"); }//sets the value of the semaphore int valueforsetsem = 0; cout << "Please input the value to set SEM:"; Cin >> Valueforsetsem; Union Mysemun SetValue; Setvalue.val = Valueforsetsem; Set the semaphore if (Semctl (semid,0,setval,setvalue)! = 0) {err_exit ("Semctl setval error"); }//Enter the critical section sem_p (Semid); cout << "Hello xiaofang!" << Endl; Exit Critical Zone Sem_v (SEMID); return 0;}
Practice 2: Threading and Semaphore synthesis Practice Union mysemun{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)//};//encapsulates V operation int sem_v (int semid) {struct Sembuf buf = {0,+1,0}; Return Semop (semid,&buf,1);} Package P operation int sem_p (int semid) {struct Sembuf buf = {0,-1,0};; Return Semop (semid,&buf,1);} unsigned long long int count = 0;void *threadforaddcount (void *arg) {int semid = *static_cast<int *> (ARG); for (;;) {sem_p (Semid); + + count; Sem_v (Semid); } pthread_exit (NULL);} void *threadforprintcount (void *arg) {for (;;) {cout << "count =" << count << Endl; Sleep (1); } pthread_exit (NULL);} int main () {//create or get semaphore int semid = Semget (0x12345670,1,0666| Ipc_creat); if (Semid = =-1) {err_exit ("Semget error"); }//Set the semaphoreThe value of int valueforsetsem = 0; cout << "Please input the value to set SEM:"; Cin >> Valueforsetsem; Union Mysemun SetValue; Setvalue.val = Valueforsetsem; Set the semaphore if (Semctl (semid,0,setval,setvalue)! = 0) {err_exit ("Semctl setval error"); } pthread_t addthread[2]; pthread_t Printthread; Create thread for (int i = 0; i < 2; ++i) {pthread_create (&addthread[i],null,threadforaddcount,&semid); } pthread_create (&printthread,null,threadforprintcount,null); Wait for the thread to terminate for (int i = 0; i < 2; ++i) {pthread_join (addthread[i],null); } pthread_join (Printthread,null); return 0;} void Err_exit (std::string str) {perror (Str.c_str ()); Exit (exit_failure);}
attached -makefile
CC = g++ Cppflags =-wall-g-pthreadbin = mainsources = $ (bin.=.cpp). Phony:clean All: $ (BIN) $ (BIN): $ (SOURCES) Clean: -RM-RF $ (BIN) Bin/obj/core
Linux semaphore Practice (2)