| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 593 人关注过本帖
标题:c语言程序设计实验报告求助
只看楼主 加入收藏
cjqyy
Rank: 1
等 级:新手上路
帖 子:1
专家分:0
注 册:2010-6-23
收藏
 问题点数:0 回复次数:0 
c语言程序设计实验报告求助
实验报告必须有以下内容:
1. 实验内容描述与需求分析
2. 概要设计(数据结构、算法设计)
3. 调试、分析与实验结果
4. 总结
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>

#define WRITER 1   // 生产者数目

#define READER 2   // 消费者数目

#define MAXNUM 10 // 缓冲数目

int  num2=1,num1=1;//读者,写者次数
pthread_mutex_t rmutex; // 读者互斥信号量, 一次只有一个线程访问缓冲
pthread_mutex_t wmutex; // 写者互斥信号量, 一次只有一个线程访问缓冲
int rcount;//现在读者数目
int r_id = 0; //读者id

void *R(void *arg)//读者
{
 
 int id = ++r_id;
 while(num2 <= MAXNUM)
 {
    // 用sleep的数量可以调节读者和写者的速度,便于观察
    sleep(2);
 
  
    pthread_mutex_lock(&rmutex);//开始读
    if( rcount==0 )
     pthread_mutex_lock(&wmutex);//判定是否在写
    rcount+=1;
    pthread_mutex_unlock(&rmutex);//也给别读者一起读
    printf("%d 号读者,开始第 %d次读书 \n", id, num2);
    sleep(2);
      pthread_mutex_lock(&rmutex);//读完
    rcount-=1;
    if( rcount==0 )
     pthread_mutex_unlock(&wmutex);//判定是否可以写
    printf("%d 号读者,读完\n", id);
    pthread_mutex_unlock(&rmutex);//读者读完
    num2+=1;
 }
 return NULL;
}

void *W(void *arg)//写者
{
 while(num1 <= MAXNUM)
 {
  // 用sleep的数量可以调节读者和写者的速度,便于观察
    sleep(1);
    pthread_mutex_lock(&wmutex);//开始写
    printf("写者第 %d次写书 \n", num1);
    sleep(3);
    pthread_mutex_unlock(&wmutex);//写完
    num1+=1;
 }
 return NULL;
}

int max(int a, int b)
{
 return (a>b)? a : b;
}

int main()
 
{
 pthread_t id1[WRITER];

  pthread_t id2[READER];

  int i;
 int ret[max(READER,WRITER)];// 初始化同步信号量


 // 创建N个写者线程
 for(i = 0; i < WRITER; i++)

 {
    ret[i] = pthread_create(&id1[i], NULL, &W, (void *)(&i));

      if(ret[i] != 0)
   
   {
    printf("Writer %d creation failed \n", i);
    exit(1);
   }
 }
 //创建N个读者线程
 
  for(i = 0; i < READER; i++)

  {
    ret[i] = pthread_create(&id2[i], NULL, &R, NULL);

      if(ret[i] != 0)
   
      {
    printf("Reader %d creation failed \n", i);
    exit(1);
         }
  }
//销毁线程
  pthread_join(id1[0],NULL);

  pthread_join(id2[0],NULL);

 
  printf("OK,结束!\n");

  exit(0);


}
那位大侠帮我分析下,谢谢了
搜索更多相关主题的帖子: 实验报告 c语言 程序设计 
2010-06-23 00:11
快速回复:c语言程序设计实验报告求助
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.017289 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved