1#include<stdio.h>
2 #include<pthread.h>
3 #include<string.h>
4 //打开图片文件
5 FILE *fg=NULL;
6 //打开需要复制的文件
7 FILE *fg1=NULL;
8 //互斥锁
9 pthread_mutex_t mutex;
10 void *callBack1(void *arg)
11 {
12 //计算文件大小
13 long len;
14 fseek(fg,0,SEEK_END);//偏移至尾部
15 len=ftell(fg);//文件大小
16 char c=0;
17 long i=0;
18 while(i<len/2)
19 {
20 /****临界区***/
21 pthread_mutex_lock(&mutex);//上锁
22
23 fread(&c,1,1,fg);
24 fwrite(&c,1,1,fg1);
25 i++;
26
27 pthread_mutex_unlock(&mutex);//解锁
28 /****临界区***/
29
30 }
31 void *callBack2(void *arg)
32 {
33 //计算文件大小
34 long len;
35 fseek(fg,0,SEEK_END);//偏移至尾部
36 len=ftell(fg);//文件大小
37 char c=0;
38 long i=len/2;
39 fseek(fg,-len/2,SEEK_SET);
40 while(i<=len)
41 {
42 /****临界区***/
43 pthread_mutex_lock(&mutex);//上锁
44
45 fread(&c,1,1,fg);
46 fwrite(&c,1,1,fg1);
47 i++;
48
49 pthread_mutex_unlock(&mutex);//解锁
50 /****临界区***/
51 }
52 }
53 int main(int argc, const char *argv[])
54 {
55 //创建互斥锁
56 if(pthread_mutex_init(&mutex,NULL)!=0)
57 {
58 perror("pthread_mutex_init");
59 return -1;
60 }
61 printf("mutex_init success\n");
62 //打开图片文件
63 fg=fopen("./1.png","r");
64 //打开需要复制的文件
65 fg1=fopen("./3.png","a+");
66 pthread_t tid1,tid2;
67 //创建线程,拷贝前半部分
68 if(pthread_create(&tid1,NULL,callBack1,(void*)&fg)!=0)
69 {
70 perror("pthread_mutex_create");
71 return -1;
72 }
73 //创建线程,拷贝后半部分
74 if(pthread_create(&tid2,NULL,callBack1,NULL)!=0)
75 {
76 perror("pthread_mutex_create");
77 return -1;
78 }
79 pthread_join(tid1,NULL);
80 pthread_join(tid2,NULL);
81 //销毁互斥锁
82 pthread_mutex_destroy(&mutex);
83 fclose(fg);
84 fclose(fg1);
85 return 0;
86 }
cpypthread.c 81,16-15 Top