標籤: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 }
線程題--拆分檔案