1.完成图片拷贝,要求-个线程拷贝- 半,另个线程拷另-半。
#include "head.h"
#include "pthread.h"
char buf;
pthread_mutex_t mutex;
void* callback1(void *arg)
{
int pd1=open("./b94f05b4b5acc618ffa261c30ee6cc241340190821.png",O_RDONLY);
int pd2=open("./1.png",O_RDWR|O_CREAT,0664);
if(pd1<0 || pd2<0)
{
perror("open");
}
off_t i=(lseek(pd1,0,SEEK_END));
off_t now=lseek(pd1,0,SEEK_SET);
lseek(pd2,0,SEEK_SET);
for(int j=0;j<i/2;j++)
{
pthread_mutex_lock(&mutex);
lseek(pd1,now,SEEK_SET);
lseek(pd2,now,SEEK_SET);
read(pd1,&buf,1);
write(pd2,&buf,1);
now=lseek(pd1,0,SEEK_CUR);
pthread_mutex_unlock(&mutex);
}
pthread_exit(NULL);
}
void* callback2(void *arg)
{
off_t i;
int pd1=open("./b94f05b4b5acc618ffa261c30ee6cc241340190821.png",O_RDONLY);
int pd2=open("./1.png",O_RDWR|O_CREAT,0664);
if(pd1<0 || pd2<0)
{
perror("open");
}
i=(lseek(pd1,0,SEEK_END))/2;
off_t now=lseek(pd1,i,SEEK_SET);
for(int j=i;j<(2*i);j++)
{
pthread_mutex_lock(&mutex);
lseek(pd1,now,SEEK_SET);
lseek(pd2,now,SEEK_SET);
read(pd1,&buf,1);
write(pd2,&buf,1);
now=lseek(pd1,0,SEEK_CUR);
pthread_mutex_unlock(&mutex);
}
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
pthread_t tid1,tid2;
if(pthread_create(&tid1,NULL,callback1,NULL)!=0)
{
fprintf(stderr,"pthread_create 失败\n");
return -1;
}
if(pthread_create(&tid2,NULL,callback2,NULL)!=0)
{
fprintf(stderr,"pthread_create 失败\n");
return -1;
}
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
return 0;
}
运行结果:
2.创建两个线程,要求一个线程从文件中读取数据, 另个线程将读取到的数据打印到终端, 类似cat-个文件。文件cat完后,要结束进程
#include "head.h"
#include "pthread.h"
#include "semaphore.h"
char buf;
int res=1;
sem_t sem1;
sem_t sem2;
void* callback1(void *arg)
{
int pd1=open("./16_zy.c",O_RDONLY);
if(pd1<0)
{
perror("open");
}
off_t i=(lseek(pd1,0,SEEK_END));
off_t now=lseek(pd1,0,SEEK_SET);
for(int j=0;j<i;j++)
{
if(sem_wait(&sem1)<0)
{
perror("sem_wait");
pthread_exit(NULL);
}
lseek(pd1,now,SEEK_SET);
res=read(pd1,&buf,1);
now=lseek(pd1,0,SEEK_CUR);
if(sem_post(&sem2)<0)
{
perror("sem_post");
pthread_exit(NULL);
}
}
res=0;
pthread_exit(NULL);
}
void* callback2(void *arg)
{
off_t i;
int pd1=open("./16_zy.c",O_RDONLY);
if(pd1<0)
{
perror("open");
}
while(res)
{
if(sem_wait(&sem2)<0)
{
perror("sem_wait");
pthread_exit(NULL);
}
write(1,&buf,1);
if(sem_post(&sem1)<0)
{
perror("sem_post");
pthread_exit(NULL);
}
}
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
if(sem_init(&sem1,0,1)<0)
{
perror("sem_init");
return -1;
}
if(sem_init(&sem2,0,0)<0)
{
perror("sem_init");
return -1;
}
pthread_t tid1,tid2;
if(pthread_create(&tid1,NULL,callback1,NULL)!=0)
{
fprintf(stderr,"pthread_create 失败\n");
return -1;
}
if(pthread_create(&tid2,NULL,callback2,NULL)!=0)
{
fprintf(stderr,"pthread_create 失败\n");
return -1;
}
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
return 0;
}
运行结果