2024-2-21-多线程基础作业
作业:
源代码:
#include <myhead.h>
#define MAXSIZE 64
//定义要传递的结构体类型
struct Info
{const char *src;const char *dest;int len;
};
int get_file_len(const char *srcfile, const char *destfile)
{//以只读的形式打开源文件int srcfd, destfd;if ((srcfd = open(srcfile, O_RDONLY)) == -1){perror("open srcfile error");return -1;}//以只写创建的形式打开目标文件if ((destfd = open(destfile, O_WRONLY | O_CREAT | O_TRUNC, 0664)) == -1){perror("open destfile error");return -1;}//求源文件的大小int len = lseek(srcfd, 0, SEEK_END);//关闭两个文件close(srcfd);close(destfd);return len;
}
void copy_file(const char *srcfile, const char *destfile, int start, int len)
{int srcfd = -1, destfd = -1;//处理主线程中传过来的数据if ((srcfd = open(srcfile, O_RDONLY)) == -1){printf("open error\n");return;}if ((destfd = open(destfile, O_WRONLY | O_CREAT | O_TRUNC, 0664)) == -1){printf("open error\n");return;}lseek(srcfd, start, SEEK_SET);lseek(destfd, start, SEEK_SET);char buf[MAXSIZE] = "";int sum = 0;while (1){int res = read(srcfd, buf, sizeof(buf));sum += res; //将每次读取的数据放入sum中if (sum >= len || res - (sum - len)){write(destfd, buf, res - (sum - len)); //将最后一次的内容写入break;}//将读取的数据写入目标文件write(destfd, buf, res);close(srcfd);close(destfd);return;}
}//定义分支线线程1
void *task1(void *arg)
{struct Info buf = *((struct Info *)arg);copy_file(buf.src, buf.dest, 0, buf.len);
}void *task2(void *arg)
{//处理主线程中传过来的数据struct Info buf = *((struct Info *)arg);copy_file(buf.src, buf.dest, buf.len / 2, buf.len);
}int main(int argc, const char *argv[])
{// if (argc != 4)// {// printf("input file error\n");// printf("usage:./a.out srcfile destfile\n");// return -1;// }// int len = get_file_len(argv[3], argv[4]);// sleep(1);char *srcfile="./1.txt";char *destfile="./2.txt";int len = get_file_len(srcfile, destfile);//定义一个结构体变量struct Info buf = {srcfile, destfile, len};sleep(1);pthread_t tid1, tid2;//创建线程1if (pthread_create(&tid1, NULL, task1, &buf) != 0) //向分支线程传递一个数据{printf("tid create error\n");return -1;}//创建线程2if (pthread_create(&tid2, NULL, task2, &buf) != 0) //向分支线程传递一个数据{printf("tid create error\n");return -1;}//回收资源pthread_join(tid1, NULL);pthread_join(tid2, NULL);sleep(5);printf("拷贝成功\n");return 0;
}
效果图: