使用信号量的线程同步实验
题目要求:父亲往盘子里放水果(苹果和香蕉),儿子只能取苹果,女儿只能取香蕉,使用信号量的线程同步实验实现该程序。
源码:
1 #include <stdio.h> 2 #include <string.h> 3 #include <semaphore.h> 4 #include <pthread.h> 5 #include <sys/types.h> 6 #include <unistd.h> 7 sem_t sp; //定义信号量 8 sem_t sa; //父亲放香蕉,女儿取水果(香蕉) 9 sem_t so; //父亲放苹果,儿子拿苹果 10 void *procf(void *arg) //father放苹果线程 11 { while(1){ 12 sem_wait(&sp); //P操作 13 printf("放了苹果\n"); 14 sem_post(&sa); //V操作 15 sleep(7); 16 }} 17 void *procm(void *arg) //父亲放香蕉线程 18 { while(1){ 19 sem_wait(&sp); 20 printf("放了香蕉\n"); 21 sem_post(&so); 22 sleep(3); 23 24 }} 25 void *procs(void *arg) //儿子吃苹果的线程 26 {while(1){ 27 sem_wait(&so); 28 printf("吃了苹果\n"); 29 sem_post(&sp); 30 sleep(2); 31 }} 32 void *procd(void *arg) //女儿吃香蕉的线程 33 { 34 while(1){ 35 sem_wait(&sa); 36 printf("吃了香蕉\n"); 37 sem_post(&sp);//sleep(5); 38 }} 39 main() 40 { e 41 42 pthread_t fatherAppale; //定义线程 43 pthread_t fatherBanala; 44 pthread_t son; 45 pthread_t daughter; 46 sem_init(&sp, 0, 1); //信号量初始化 47 sem_init(&sa, 0, 0); 48 sem_init(&so, 0, 0); 49 pthread_create(&fatherAppale,NULL,procf,NULL); //创建线程 50 pthread_create(&fatherBanala,NULL,procm,NULL); 51 pthread_create(&daughter,NULL,procd,NULL); 52 pthread_create(&son,NULL,procs,NULL); 53 while(1){} 54 }
编译命令:gcc dingxiaowei.c -o dingxiaowei -lpthread
运行命令:./dingxiaowei
显示结果:父亲放置苹果
儿子取苹果
父亲放香蕉
女儿取香蕉
· 。。。
感谢来访,共同学习!