1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
| #include <stdio.h> #include <string.h> #include <sys/stat.h> #include <time.h> #include <stdlib.h> #include <fcntl.h> #include <unistd.h> #include <pthread.h> pthread_mutex_t mutex[135]; pthread_t thrd[135]; int qwq[135]; void makeReports(int *idx) { char names1[55], names2[55], ss[15]; pthread_mutex_lock(&mutex[*idx]); sprintf(names1, "books/book%d.txt", *idx); sprintf(names2, "reports/report%d.txt", *idx); int rid=open(names1, O_RDONLY); int wid=open(names2, O_RDWR | O_CREAT, 0664); struct stat statbuf; stat(names1,&statbuf); int bookLen=statbuf.st_size; while(read(rid, ss, 10)!=0) { write(wid, ss+rand()%10, 1); } close(rid); pthread_mutex_unlock(&mutex[*idx]); int cnt=bookLen/10; while(cnt) { int nu=rand()%130; pthread_mutex_lock(&mutex[nu]); sprintf(names1, "books/book%d.txt", nu); rid = open(names1, O_RDONLY); while(read(rid, ss, 4)!=0 && cnt>0) { write(wid, ss+rand()%4, 1); cnt--; } close(rid); pthread_mutex_unlock(&mutex[nu]); } close(wid); printf("Done %d\n", *idx); } int main() { srand(time(NULL)); int huaq[135]; for(int i=0; i<130; i++) { pthread_mutex_init(&mutex[i], NULL); huaq[i] = i; } for(int i=0; i<130; i++) { int j=i; pthread_create(&thrd[i], NULL, (void *)makeReports, &huaq[i]); } for(int i=0; i<130; i++) pthread_join(thrd[i], NULL); return 0; }
|