题目描述:
现有一个小巷,除安全岛可容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路段 ",A_people); V(A); V(A_S); island_people++; printf("A%d此时在岛上,此时岛上有%d人 ",A_people,island_people); P(B_S); island_people--; V(island);//只要踏上另一段路,就释放island资源 printf("A%d正在走B-S路段 ",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路段 ",B_people); V(B); V(B_S); island_people++; printf("B%d此时在岛上,此时岛上有%d人 ",B_people,island_people); P(A_S); island_people--; V(island);//只要踏上另一段路,就释放island资源 printf("B%d正在走A-S路段 ",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); }