标签: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=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 }
标签:thread fputc log int utc code bsp and asp
原文地址:https://www.cnblogs.com/jiaan/p/9392551.html