zoukankan      html  css  js  c++  java
  • 线程题--拆分文件

    将一个文件的前一半复制到一个文件,后一半复制到另一个文件,通过两个线程:

     1 #include<stdio.h>
     2 #include<semaphore.h>
     3 
     4 #include<pthread.h>
     5 
     6 FILE *fs,*fd1,*fd2;
     7 
     8 sem_t sem1,sem2; 定义信号变量
     9 
    10 void *thread_handler1(void *arg)
    11 {
    12     char c;
    13     int count=0;
    14     sem_wait(&sem1);
    15     printf("%d
    ",*((int *)arg));
    16    //this from https://i.cnblogs.com/EditPosts.aspx?opt=1
         while((c = fgetc(fs)) > 0) 17 { 18 fputc(c,fd1); 19 if(++count >= *((int *)arg))判断是否复制到中间 20 break; 21 } 22 fclose(fd1); 23 24 sem_post(&sem2); 25 } 26 27 void *thread_handler2(void *arg) 28 { 29 char c; 30 // fseek(); 31 sem_wait(&sem2); 32 printf("enter "); 33 while((c = fgetc(fs)) > 0) 34 { 35 fputc(c,fd2); 36 } 37 fclose(fd2); 38 } 39 40 int main(int argc, const char *argv[]) 41 { 42 pthread_t thread1,thread2;定义线程变量 43 44 fs = fopen("copy_half.c","r"); 45 fd1 = fopen("text1.txt","w");打开文件 46 fd2 = fopen("text2.txt","w"); 47 int middle,i; 48 fseek(fs,0,SEEK_END); 49 i = ftell(fs); 50 middle = i/2; 51 fseek(fs,0,SEEK_SET); 52   //from https://i.cnblogs.com/EditPosts.aspx?opt=1 53 sem_init(&sem1,0,1); 54 sem_init(&sem2,0,0); 55 pthread_create(&thread1,NULL,thread_handler1,(void *)&middle);开第一个线程 56 pthread_create(&thread2,NULL,thread_handler2,(void *)&middle);开第二个线程 57 58 pthread_join(thread1,NULL);等待线程结束 59 pthread_join(thread2,NULL); 60 61 sem_destroy(&sem1);销毁信号量 62 sem_destroy(&sem2); 63 64 65 66 return 0; 67 }
  • 相关阅读:
    lampp、xampp安装文档
    tomcat下配置https方式
    1.6:怎么学习Linux
    1.5:linux的应用领域
    1.3:linux的优点和缺点
    1.4:Linux发行版本详解
    1.2:liunx和unix的区别
    1.1:Linux系统简介
    mysql中获取表名&字段名的查询语句
    kettle组件-输出
  • 原文地址:https://www.cnblogs.com/jiaan/p/9392551.html
Copyright © 2011-2022 走看看