day6线程

1.创建两个线程,一个拷贝前半部分,另一个拷贝后半部分,用上互斥锁

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <head.h>
pthread_mutex_t mutex;
struct msg
{
    int fd_r;
    int fd_w;
    off_t size;
};

void *callBack(void *arg)
{
    int fd_r=((struct msg*)arg)->fd_r;
    int fd_w=((struct msg*)arg)->fd_w;
    char a=0;
    int size=((struct msg*)arg)->size;
    lseek(fd_r,0,SEEK_SET);
    lseek(fd_w,0,SEEK_SET);
    pthread_mutex_lock(&mutex);
    for(int i=0;i<size/2;i++)
    {
        read(fd_r,&a,sizeof(char));
        write(fd_w,&a,sizeof(char));
    }
    printf("前半部分拷贝完成\n");
    pthread_mutex_unlock(&mutex);
    pthread_exit(NULL);                                           
}
int main(int argc, const char *argv[])
{
    pthread_mutex_init(&mutex,NULL);
    int fd_r=open("1.png",O_RDONLY);
    if(fd_r<0)
    {
        ERR_MSG("open");
        return -1;
    }
    int fd_w=open("write.png",O_WRONLY | O_CREAT | O_TRUNC,0664);
    if(fd_w<0)
    {
        ERR_MSG("open");
        return -1;
    }
    off_t size=lseek(fd_r,0,SEEK_END);
    struct msg info;
    info.fd_r=fd_r;
    info.fd_w=fd_w;
    info.size=size;
    pthread_t tid;                                                  
    if(pthread_create(&tid,NULL,callBack,(void *)&info)!=0)
    {
        fprintf(stderr,"pthread_create failed __%d__\n",__LINE__);
        return -1;
    }
    char b;
    pthread_join(tid,NULL);
    lseek(fd_r,size/2,SEEK_SET);
    lseek(fd_w,size/2,SEEK_SET);
    pthread_mutex_lock(&mutex);
    for(int i=size/2;i<size;i++)
    {
        read(fd_r,&b,sizeof(char));
        write(fd_w,&b,sizeof(char));
    }
    printf("后半部分拷贝完成\n");
    pthread_mutex_unlock(&mutex);
    close(fd_r);
    close(fd_w);
    pthread_mutex_destroy(&mutex);
    return 0;
}

 2.思维导图

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值