您的位置:首页 > 其它

线程同步机制(1)---无名信号量

2014-01-01 16:04 190 查看
#include <stdio.h>

#include <stdlib.h>

#include <fcntl.h>

#include <string.h>

#include <errno.h>

#include <pthread.h>

#include <semaphore.h>

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);

}

阅读(156) | 评论(0) | 转发(0) |

0
上一篇:进程间通信方式(2)---信号

下一篇:vim基本配置

相关热门文章
欢迎无名人士1990在ChinaUnix...

Chanel Bags UK

信号量与自旋锁 |Linux,信号量...

C语言之位域

武汉依黛天娇服饰有限公司命中...

linux 常见服务端口

【ROOTFS搭建】busybox的httpd...

什么是shell

linux socket的bug??

linux的线程是否受到了保护?...

Oracle VM server 如何删除vm ...

kvm上的两台windows虚拟机不能...

关于ip_route_output_key和ip_...

linux inode中磁盘地址列表有...

LNMP 老是会出现502?

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