IO进程线程第六天(8.3)线程,线程函数+XMind

创建两个线程:其中一个线程拷贝前半部分,另一个线程拷贝后半部分。

只允许开一份资源,且用互斥锁方式实现。

#include<stdio.h>
#include<head.h>
#include<pthread.h>
struct file
{
    int fp; 
    int fq; 
    off_t size;
};
pthread_mutex_t suo;
void* buf1(void* arg)
{
    char c;
    int fp=((struct file*)arg)->fp;
    int fq=((struct file*)arg)->fq;
    off_t size=((struct file*)arg)->size;
    pthread_mutex_lock(&suo);
    lseek(fp,0,SEEK_SET);
    lseek(fq,0,SEEK_SET);
    for(int i=0;i<size/2;i++)//循环读写,一个一个读,一个一个写,写前一半部分
    {   
        read(fp,&c,1);
        write(fq,&c,1);
    }   
    printf("前半部分拷贝完毕\n");
    pthread_mutex_unlock(&suo);
    pthread_exit(NULL);
}
void* buf2(void* arg)
{
    char c;
    int fp=((struct file*)arg)->fp;
    int fq=((struct file*)arg)->fq;
    off_t size=((struct file*)arg)->size;
    pthread_mutex_lock(&suo);
    lseek(fp,size/2,SEEK_SET);
    lseek(fq,size/2,SEEK_SET);
    for(int i=(size/2);i<size;i++)//循环读写,一个一个读,一个一个写,写后一半部分
    {   
        read(fp,&c,1);
        write(fq,&c,1);
    }   
    printf("后半部分拷贝完毕\n");
    pthread_mutex_unlock(&suo);
    pthread_exit(NULL);
}

int main(int argc, const char *argv[])
{
    pthread_mutex_init(&suo,NULL);
    int fp=open("/home/ubuntu/图片/下午 趴在桌子的女孩4k动漫壁纸3840x2160_彼岸图网.jpg",O_RDONLY);//打开要拷贝的图片
    if(fp<0)
    {   
        ERR_MSG("fp open");
        return -1; 
    }   
    int fq=open("1.jpg",O_WRONLY|O_CREAT|O_TRUNC,0664);//打开拷贝成的图片
    if(fq<0)
    {   
        ERR_MSG("fq open");
        return -1; 
    }   
    off_t size=lseek(fp,0,SEEK_END);
    struct file ph; 
    ph.fp=fp;
    ph.fq=fq;
    ph.size=size;
    pthread_t pt1;//创建子线程
    if(pthread_create(&pt1,NULL,buf1,(void *)&ph)!=0)//判断线程是否创建成功
    {   
        fprintf(stderr,"errno");
        return -1; 
    }   
    pthread_t pt2;//创建子线程
    if(pthread_create(&pt2,NULL,buf2,(void *)&ph)!=0)//判断线程是否创建成功
    {   
        fprintf(stderr,"errno");
        return -1; 
    }   
    pthread_join(pt1,NULL);
    pthread_join(pt2,NULL);
    pthread_mutex_destroy(&suo);                                                                                                                                                                                                                                                         
    close(fp);//关闭被拷贝的图片
    close(fq);//关闭拷贝的图片

    return 0;
}  

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值