線程題--拆分檔案

來源:互聯網
上載者:User

標籤:thread   fputc   log   int   utc   code   bsp   and   asp   

將一個檔案的前一半複製到一個檔案,後一半複製到另一個檔案,通過兩個線程:

 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\n",*((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\n");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=153 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 }

 

線程題--拆分檔案

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.