多线程编程的实例练习

使用两个线程完成两个文件的拷贝,分支线程1拷贝前一半,分支线程2拷贝后一半,主线程回收两个分支线程的资源

// 使用两个线程完成两个文件的拷贝
// 分支线程1拷贝前一半,分支线程2拷贝后一半
// 主线程回收两个分支线程的资源
#include <myhead.h>

// 定义一个用于传递数据的结构体类型
struct File
{
    int fd1;   // 源文件描述符
    int fd2;   // 目标文件描述符
    int start; // 拷贝的起始位置
    int end;   // 拷贝的结束位置
};

void *task1(void *arg)
{
    // 获取结构体变量
    struct File *file = (struct File *)arg;
    // 置位光标
    off_t bytes_read = file->start;
    // 定义缓冲区用于数据读写
    char buf[128];
    lseek(file->fd1, file->start, SEEK_SET);
    lseek(file->fd2, file->start, SEEK_SET);
    // 读取源文件
    while (bytes_read < file->end)
    {
        int count = read(file->fd1, buf, sizeof(buf));
        if (count <= 0)
            return 0;
        // 写目标文件
        write(file->fd2, buf, count);
        bytes_read += count;
    }
}

void *task2(void *arg)
{
    // 获取结构体变量
    struct File *file = (struct File *)arg;
    // 置位光标
    off_t bytes_read = file->start;
    // 定义缓冲区用于数据读写
    char buf[128];
    lseek(file->fd1, file->start, SEEK_SET);
    lseek(file->fd2, file->start, SEEK_SET);
    // 读取源文件
    while (bytes_read < file->end)
    {
        int count = read(file->fd1, buf, sizeof(buf));
        if (count <= 0)
            return 0;
        // 写目标文件
        write(file->fd2, buf, count);
        bytes_read += count;
    }
}

int main(int argc, const char *argv[])
{
    if (argc != 3)
    {
        printf("使用方法: %s <源文件> <目标文件>\n", argv[0]);
        return EXIT_FAILURE;
    }
    // 打开两个文件
    int source_fd = -1, copy_fd = -1;
    source_fd = open(argv[1], O_RDONLY);
    copy_fd = open(argv[2], O_WRONLY | O_CREAT | O_TRUNC, 0777);

    // 检查文件打开是否成功
    if (source_fd == -1 || copy_fd == -1)
    {
        printf("文件打开失败\n");
        return EXIT_FAILURE;
    }
    // 定义结构体变量
    struct File file;
    file.fd1 = source_fd;
    file.fd2 = copy_fd;

    // 获取源文件大小
    int file_size = lseek(source_fd, 0, SEEK_END);
    int half_size = file_size / 2;

    // 定义线程变量
    pthread_t tid1, tid2;

    // 定义结构体变量
    file.start = 0;
    file.end = half_size;
    // 创建两个线程
    if (pthread_create(&tid1, NULL, task1, &file) != 0)
    {
        printf("tid1 创建失败\n");
        return -1;
    }
    printf("tid1 创建成功\n");
    // 改结构体变量
    file.start = half_size;
    file.end = file_size;
    if (pthread_create(&tid2, NULL, task2, &file) != 0)
    {
        printf("tid2 创建失败\n");
        return -1;
    }
    printf("tid2 创建成功\n");
    // 阻塞等等线程的结束
    pthread_join(tid1, NULL);
    pthread_join(tid2, NULL);

    return 0;
}

奇怪的用法增加了

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值