題目描述:
現有一個小巷,除安全島可容2人暫時停身外,僅能容一人通過。A,B兩頭都允許行人進出,試用信號量和PV操作設計一個算法,讓兩頭的行人順利通過小巷。
解題模型:
sem_t A_S;//A-S路段 sem_t B_S;//B-S路段 sem_t island;//島 sem_t A;//對A頭的人數進行唯一操作 sem_t B;//對B頭人數進行唯一操作 sem_t IS;//對island島上的人進行唯一操作 void* A() { while(1) { P(island);//先取到island資源 P(A-S); //取 A-S路段 資源,上鎖 P(A); //唯一操作A-people A_people--; {走 A-S } V(A); //A-people操作完成,解鎖 V(A-S); //釋放 A-S路段 資源 P(B-S); //請求踏上 B-S路段 ,上鎖 V(island); //當A過來的人踏上 B-S路段,則釋放island資源,保證資源最大化 {走B-S }; V(B-S); //解鎖 } } void* B() { while(1) { P(island);//先取到island資源 P(B-S); //取 B-S路段 資源,上鎖 P(B); //唯一操作B-people B_people--; {走 B-S } V(B);//B-people操作完成,解鎖 V(B-S);//釋放 B-S路段 資源 P(A-S);//請求踏上 A-S路段 ,上鎖 V(island); //當B過來的人踏上 A-S路段,則釋放island資源,保證資源最大化 {走A-S }; V(A-S); //解鎖 } }
程序源碼:
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <pthread.h> #include<semaphore.h> #define P sem_wait #define V sem_post #define A_S &A_S_road #define B_S &B_S_road #define island &AB_island #define A &A_peo #define B &B_peo sem_t A_S_road;//臨界資源:A-S路段 sem_t B_S_road;//臨界資源:B-S路段 sem_t AB_island;//島 初值為2 sem_t A_peo;//對A頭的人數進行唯一操作 sem_t B_peo;//對B頭人數進行唯一操作 int A_people=5;//A頭的人數 int B_people=5;//B頭的人數 int island_people=0;//記錄島上的人數 void* process_A(void *p) { while(A_people > 0) { P(island); P(A_S); P(A); A_people--; printf("A%d正在走A-S路段\n",A_people); V(A); V(A_S); island_people++; printf("A%d此時在島上,此時島上有%d人\n",A_people,island_people); P(B_S); island_people--; V(island);//只要踏上另一段路,就釋放island資源 printf("A%d正在走B-S路段\n",A_people); V(B_S); } } void* process_B(void *p) { while(B_people > 0) { P(island); P(B_S); P(B); B_people--; printf("B%d正在走B-S路段\n",B_people); V(B); V(B_S); island_people++; printf("B%d此時在島上,此時島上有%d人\n",B_people,island_people); P(A_S); island_people--; V(island);//只要踏上另一段路,就釋放island資源 printf("B%d正在走A-S路段\n",B_people); V(A_S); } } int main() { sem_init(A_S, 0, 1); //A-S路段是臨界資源,初值為1 sem_init(B_S, 0, 1); //B-S路段是臨界資源,初值為1 sem_init(island, 0, 2); //島上可停留2人,island初值為2 sem_init(A, 0, 1); //操作A-people的互斥資源 sem_init(B, 0, 1); //操作B-people的互斥資源 pthread_t tid0; pthread_t tid1; pthread_create(&tid0, NULL, process_A, NULL); pthread_create(&tid1, NULL, process_B, NULL); pthread_exit(0); }