您的位置:首页 > 其它

使用信号量的线程同步实验

2013-05-23 11:43 295 查看
题目要求:父亲往盘子里放水果(苹果和香蕉),儿子只能取苹果,女儿只能取香蕉,使用信号量的线程同步实验实现该程序。

源码:

#include <stdio.h>
#include <string.h>
#include <semaphore.h>
#include <pthread.h>
#include <sys/types.h>
#include <unistd.h>
sem_t sp;  //定义信号量
sem_t sa;  //父亲放香蕉,女儿取水果(香蕉)
sem_t so;  //父亲放苹果,儿子拿苹果
void *procf(void *arg) //father放苹果线程
{   while(1){
sem_wait(&sp); //P操作
printf("放了苹果\n");
sem_post(&sa); //V操作
sleep(7);
}}
void *procm(void *arg)  //父亲放香蕉线程
{ while(1){
sem_wait(&sp);
printf("放了香蕉\n");
sem_post(&so);
sleep(3);

}}
void *procs(void *arg)  //儿子吃苹果的线程
{while(1){
sem_wait(&so);
printf("吃了苹果\n");
sem_post(&sp);
sleep(2);
}}
void *procd(void *arg)  //女儿吃香蕉的线程
{
while(1){
sem_wait(&sa);
printf("吃了香蕉\n");
sem_post(&sp);//sleep(5);
}}
main()
{ e

pthread_t fatherAppale;  //定义线程
pthread_t fatherBanala;
pthread_t son;
pthread_t daughter;
sem_init(&sp, 0, 1);  //信号量初始化
sem_init(&sa, 0, 0);
sem_init(&so, 0, 0);
pthread_create(&fatherAppale,NULL,procf,NULL);  //创建线程
pthread_create(&fatherBanala,NULL,procm,NULL);
pthread_create(&daughter,NULL,procd,NULL);
pthread_create(&son,NULL,procs,NULL);
while(1){}
}


编译命令:gcc dingxiaowei.c -o dingxiaowei -lpthread

运行命令:./dingxiaowei

显示结果:父亲放置苹果

     儿子取苹果

     父亲放香蕉

     女儿取香蕉

·     。。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: