1.创建2个子线程,拷
总字节大小size为: 619790
A创建成功
B创建成功
A拷贝完成
A拷贝完成
ubuntu@ubuntu:X1$ ls
copy.png core k1 k1.c t1 t1.c
ubuntu@ubuntu:X1$ eog copy.png
ubuntu@ubuntu:X1$ cat k1.c
#include <head.h>
#include <pthread.h>
pthread_mutex_t mutex;
off_t size;
int fp;
int fpw;
void* TidB(void* arg);
void* TidB(void* arg)
{
pthread_mutex_lock(&mutex);
char s1 = 0;
lseek(fp,size/2,SEEK_SET);
lseek(fpw,size/2,SEEK_SET);
for(int i=size/2;i<size;i++)
{
read(fp,&s1,1);
write(fpw,&s1,1);
}
pthread_mutex_unlock(&mutex);
pthread_exit(NULL);
}
void* Atid(void* arg);
void* Atid(void* arg)
{
pthread_mutex_lock(&mutex);
char s1 = 0;
lseek(fp,0,SEEK_SET);
lseek(fpw,0,SEEK_SET);
for(int i=0;i<size/2;i++)
{
read(fp,&s1,1);
write(fpw,&s1,1);
}
pthread_mutex_unlock(&mutex);
pthread_exit(NULL);
}
int main()
{
fp = open("/home/ubuntu/Kple.png",O_RDONLY);
if(fp < 0)
{
perror("openr");
return -1;
}
fpw = open("copy.png",O_WRONLY|O_CREAT|O_TRUNC,0777);
if(fpw < 0)
{
perror("openw");
return -1;
}
size = lseek(fp,0,SEEK_END);
printf("总字节大小size为: %ld\n",size);
pthread_mutex_init(&mutex,NULL);
pthread_t tida;
pthread_t tidb;
if(pthread_create(&tida,NULL,TidB,NULL) != 0)
{
printf("pthread_create error __%d__\n",__LINE__);
return -1;
}
printf("A创建成功\n");
if(pthread_create(&tidb,NULL,Atid,NULL) != 0)
{
printf("pthread_create error __%d__\n",__LINE__);
return -1;
}
printf("B创建成功\n");
pthread_join(tida,NULL);
printf("A拷贝完成\n");
pthread_join(tidb,NULL);
printf("A拷贝完成\n");
pthread_mutex_destroy(&mutex);
close(fp);
close(fpw);
return 0;
}
贝图片文件,各线程各拷贝一办;