1.完成图片拷贝,要求一个线程拷贝一半,另一个线程拷贝另一半。
a.找临界资源,找临界区,对临界区上锁解锁即可
#include <head.h>
#include <pthread.h>
int f_y,f_m;
off_t size,offset;
//定义锁
pthread_mutex_t mutex;
//分之线程1
void* callback1(void *arg)
{
//计算文件大小
size=lseek(f_y,0,SEEK_END);
offset=0;
char a=0;
for(int i=0;i<size/2;i++)
{
//上锁
pthread_mutex_lock(&mutex);
//修改偏移量
lseek(f_y,offset,SEEK_SET);
lseek(f_m,offset,SEEK_SET);
//读数据
read(f_y,&a,1);
write(f_m,&a,1);
offset=lseek(f_y,0,SEEK_CUR);
//解锁
pthread_mutex_unlock(&mutex);
}
printf("前\n");
pthread_exit(NULL);
}
//分之线程2
void* callback2(void *arg)
{
//计算文件大小
size=lseek(f_y,0,SEEK_END);
offset=size/2;
char a=0;
for(int i=size/2;i<size;i++)
{
//上锁
pthread_mutex_lock(&mutex);
//修改偏移量
lseek(f_y,offset,SEEK_END);
lseek(f_m,offset,SEEK_END);
//读数据
read(f_y,&a,1);
write(f_m,&a,1);
offset=lseek(f_y,0,SEEK_CUR);
//解锁
pthread_mutex_unlock(&mutex);
}
printf("后\n");
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
//打开源文件
f_y=open("./1.png",O_RDONLY);
//打开目标文件
f_m=open("./2.png",O_WRONLY|O_CREAT|O_TRUNC,0664);
//创建互斥锁
pthread_mutex_init(&mutex,NULL);
//创建线程
pthread_t tid1,tid2;
if(pthread_create(&tid1,NULL,callback1,NULL)!=0)
{
fprintf(stderr,"pthread_create __%d__\n",__LINE__);
return -1;
}
if(pthread_create(&tid2,NULL,callback2,NULL)!=0)
{
fprintf(stderr,"pthread_create __%d__\n",__LINE__);
return -1;
}
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
close(f_y);
close(f_m);
//销毁锁
pthread_mutex_destroy(&mutex);
return 0;
}
2.创建两个线程,要求一个线程从文件中读取数据,另一个线程将读取到的数据打印到终端,类似cat一个文件。文件cat完毕后,要结束进程
a.读到一次数据,打印一次数据
#include <head.h>
#include <unistd.h>
//定义全局变量
char buff;
//定义信号量
sem_t sem1;
sem_t sem2;
ssize_t res;
int f;
//分之线程1
void* callback1(void *arg)
{
while(1)
{
//P操作-1
if(sem_wait(&sem1)<0)
{
perror("sem_wait");
pthread_exit(NULL);
}
while((res=read(f,&buff,1))!=0)
{
break;
}
//V操作+1
if(sem_post(&sem2)<0)
{
perror("sem_post");
pthread_exit(NULL);
pthread_exit(NULL);
}
}
pthread_exit(NULL);
}
//分之线程2
void* callback2(void *arg)
{
while(1)
{
//P操作-1
if(sem_wait(&sem2)<0)
{
perror("sem_wait");
pthread_exit(NULL);
}
//写数据到终端
write(1,&buff,1);
//V操作+1
if(sem_post(&sem1)<0)
{
perror("sem_post");
pthread_exit(NULL);
}
}
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
//打开文件
f=open("./pthread_01.c",O_RDONLY);
//创建信号量
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 __%d__\n",__LINE__);
return -1;
}
if(pthread_create(&tid2,NULL,callback2,NULL)!=0)
{
fprintf(stderr,"pthread_create __%d__\n",__LINE__);
return -1;
}
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
sem_destroy(&sem1);
sem_destroy(&sem2);
return 0;
}