Chinaunix首页 | 论坛 | 博客
  • 博客访问: 124415
  • 博文数量: 23
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 329
  • 用 户 组: 普通用户
  • 注册时间: 2013-08-04 13:23
个人简介

开心过好每天!

文章分类

全部博文(23)

文章存档

2013年(23)

分类: LINUX

2013-08-05 18:49:44

#include
#include
#include
#include
#include
#include
#include

sem_t semR,semW;

//封装PV操作
void p(sem_t *psem)
{
 if(sem_wait(psem) < 0)
 {
  perror("fail to sem_wait");
  exit(EXIT_FAILURE);
 }
}

void v(sem_t *psem)
{
 if(sem_post(psem) < 0)
 {
  perror("fail to sem_post");
  exit(EXIT_FAILURE);
 }
}

void *threadWrite(void *vptr)
{
 char buf[128] = {'\0'};
 static int count = 0;
 printf("write thread is running\n");
 while(1)
 {
  p(&semW);
  fgets(buf,sizeof(buf) - 1,stdin);
  buf[strlen(buf) - 1] = '\0';
  write(*(int *)vptr,buf,strlen(buf));
  printf("write %d byte\n",strlen(buf));
  count += strlen(buf);
  v(&semR);
     if(count >= 127)
   goto finish;
 }
finish:pthread_exit("write thread is over");
 return;
}

void *threadRead(void *vptr)
{
 char buf[128] = {'\0'};
 int lenth = 0;
 printf("thread Read is running\n");
 while(1)
 {
  p(&semR);
  lseek(*(int *)vptr,SEEK_SET,0);
  read(*(int *)vptr,buf,sizeof(buf) - 1);
  buf[strlen(buf)] = '\0';
  printf("read %d byte:%s\n",strlen(buf),buf);
  if(strlen(buf) >= 127)
   goto finish;
  v(&semW);
 }
finish:pthread_exit("threadRead is over");
 return;
}

int main(int argc,char *argv[])
{
 int fd;
 int retRead = 0,retWrite = 0;;
 pthread_t tidRead = 0,tidWrite = 0;
 void *resultOfRead = NULL,*resultOfWrite = NULL;

 //信号量初始化
 sem_init(&semR,0,0);
 sem_init(&semW,0,1);

 fd = open(argv[1],O_RDWR | O_CREAT | O_TRUNC,0666);
 if(fd < 0)
 {
  fprintf(stderr,"fail to open %s:%s\n",argv[1],strerror(errno));
  exit(EXIT_FAILURE);
 }

 retRead = pthread_create(&tidRead,NULL,threadRead,(void *)&fd);
 if(retRead != 0)
 {
  perror("fail to pthread_create read");
  exit(EXIT_FAILURE);
 }

 retWrite = pthread_create(&tidWrite,NULL,threadWrite,(void *)&fd);
 if(retWrite != 0)
 {
  perror("fail to pthread_create write");
  exit(EXIT_FAILURE);
 }

 pthread_join(tidRead,&resultOfRead);
 printf("result of writeTread:%s\n",(char *)resultOfRead);

 pthread_join(tidWrite,&resultOfWrite);
 printf("resut of readThread:%s\n",(char *)resultOfWrite);

 exit(EXIT_SUCCESS);
}

阅读(1508) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~