macosx 不允许无名信号量_线程同步机制(1)---无名信号量

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

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值