线程作业 DAY2

该代码示例展示了一个使用C语言和pthread库实现的简易多线程文件复制程序。程序通过创建两个线程分别复制文件的前半部分和后半部分,以提高效率。虽然文中提到更优化的方法是使用malloc和线程列表,但此实现对于小规模的文件复制已足够。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

作业:多线程复制文件(简易版)---时间仓促。真正合理的应该是利用malloc 及线程列表多线程复制文件。那样比设置全局变量划算得多。但两三个线程而已,就无所谓

ubuntu@ubuntu:~$ cat test4.c
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <pthread.h>
#include <fcntl.h>
#include <string.h>
int myread;
int mywrite;
int len;
pthread_t pid,pd1,pd2;
void copyfile(int myread,int mywrite,int pot,int len)//拷贝文件
{
  
  char buf[128]={'\0'};
  int count=0;
  lseek(myread,pot,SEEK_SET);
  lseek(mywrite,pot,SEEK_SET);
  while(1)
  {
   int rdfil=read(myread,buf,sizeof(buf));
   count=count+rdfil;
   if(count>len ||rdfil==0)
   {
    write(mywrite,buf,rdfil-(count-len));
    bzero(buf,sizeof(buf));
    break;
   }
   write(mywrite,buf,rdfil);
   bzero(buf,sizeof(buf));
  }
}

void *task2(void *arg)
{
//拷贝后半段
copyfile(myread,mywrite,0,len/2);
pthread_exit(NULL);
}

void *task1(void *arg)
{
//拷贝前半段
copyfile(myread,mywrite,len/2,len-len/2);
pthread_exit(NULL);
}

void *task(void *arg)
{
if(pthread_create(&pd1,NULL,task1,&pid))
{
    perror("Wrong");
    exit(-1);
}
if(pthread_create(&pd2,NULL,task2,&pid))
{
    perror("Wrong");
    exit(-1);    
}

}

pthread_join(pd1,NULL);

pthread_join(pd2,NULL);

int main(int argc,char *argv[])
{
 if(argc!=3)
 {
  perror("参数错");
  return -1;
 }
 myread=open(argv[1],O_RDONLY);
 if(myread<0)
 {
  perror("Read Wrong");
  return -1;
 }
 
 mywrite=open(argv[2],O_RDWR|O_TRUNC|O_CREAT,0664);
 if(mywrite<0)
 {
  perror("open for write wrong");
  return -1;
 }
 len=lseek(myread,0,SEEK_END);    
    
if(pthread_create(&pid,NULL,task,NULL))
{
 perror("open for write wrong");
 return -1;
}
pthread_exit(NULL);

pthread_join(pid,NULL);
return 0;

}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值