【IO】线程作业

本文介绍了两个C语言程序,分别展示了如何使用多线程进行数据交换和文件I/O操作。第一个示例中,两个线程在循环中交换字符数组的内容;第二个示例中,一个线程负责读取文件内容,另一个线程负责写入,实现文件内容的拷贝。
摘要由CSDN通过智能技术生成

 #include <stdio.h>
 #include <pthread.h>                                                                  
 #include <string.h>

 
 char buf[]="1234567";
 int key = 0;
 
 void* callback1(void*arg)
 {
     while(1)
     {
         if(key == 0)
         {
             printf("%s\n",buf);
             key=1;
         }
         
 
     }
     pthread_exit(NULL);
 }
 
 void* callback2(void*arg)
 {
 
     int i,j;
     char temp;
     while(1)
     {
         if(key == 1)
         {
             for(i=0,j=strlen(buf)-1;i<j;i++,j--)
             {
                 temp = buf[i];
                 buf[i]=buf[j];
                 buf[j] = temp;
             }
             key=0;
         }
     }   
     pthread_exit(NULL);
 }
 
 int main(int argc, const char *argv[])
 {
     pthread_t A,B;
     pthread_create(&A,NULL,callback1,NULL);
 
     pthread_create(&B,NULL,callback2,NULL);
 
 
     pthread_join(A,NULL);
     pthread_join(B,NULL);
     return 0;
 }

运行结果:

#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
 
typedef struct open{
    int fd;
    int fd2;
    off_t size;
}FUN;
 
void* func(void* arg){
    FUN* mode=(FUN*)arg;
    lseek(mode->fd,0,SEEK_SET);
    lseek(mode->fd2,0,SEEK_SET);
    char c;
    for(int i=0;i<(mode->size)/2;i++){
        read(mode->fd,&c,1);
        write(mode->fd2,&c,1);
    }
    printf("前半部分拷贝完成\n");
 
    pthread_exit(NULL);
    return NULL;
}
 
int main(int argc, const char *argv[])
{
    FUN mode;
    mode.fd=open("./1.png",O_RDONLY);
    if(mode.fd<0){
        perror("open");
        return -1;
    }
    mode.fd2=open("./2.png",O_WRONLY|O_CREAT|O_TRUNC,0664);
    if(mode.fd2<0){
        perror("open_fd2");
        return -1;
    }
    mode.size=lseek(mode.fd,0,SEEK_END);
    pthread_t tid;
    pthread_create(&tid,NULL,func,(void*)&mode);
 
    pthread_join(tid,NULL);
    char c;
    //lseek(mode.fd,(mode.size)/2,SEEK_SET);
    //lseek(mode.fd2,(mode.size)/2,SEEK_SET);                                           
    for(int i=(mode.size)/2;i<mode.size;i++){
        read(mode.fd,&c,1);
        write(mode.fd2,&c,1);
    }
    printf("全部拷贝完成\n");
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值