作业
题目一
创建两个线程:其中一个线程拷贝前半部分,另一个线程拷贝后半部分。
只允许开一份资源,且用互斥锁方式实现。 提示:找临界区---》找临界资源。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include<head.h>
pthread_mutex_t mutex;
//用来给子线程传参
struct Meg
{
int word_r;
int word_w;
off_t size;
};
//子线程打印后半段
void *soo(void *arg)
{
int word_r = ((struct Meg*)arg)->word_r;
int word_w = ((struct Meg*)arg)->word_w;
off_t size = ((struct Meg*)arg)->size;
//上锁
pthread_mutex_lock(&mutex);
lseek(word_r,size,SEEK_SET);
lseek(word_w,size,SEEK_SET);
char c = 0;
for(int i = 0;i<size;i++)
{
read(word_r,&c,1);
write(word_w,&c,1);
}
printf("后半部分打印完毕\n");
//解锁
pthread_mutex_unlock(&mutex);
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
//创建互斥锁
pthread_mutex_init(&mutex,NULL);
//主线程打开读取和写入的文件
int word_r = open("/home/linux/Pictures/1.png",O_RDONLY);
if(-1 == word_r)
{
ERR_MSG("open");
return -1;
}
int word_w = open("./1.png",O_WRONLY|O_CREAT|O_TRUNC,0777);
if(-1 == word_w)
{
ERR_MSG("open");
return -1;
}
//结构体赋值
off_t size = lseek(word_r,0,SEEK_END)/2;
struct Meg file;
file.word_r = word_r;
file.word_w = word_w;
file.size = size;
//子线程创建,并传参
pthread_t tid;
if(pthread_create(&tid,NULL,soo,(void *)&file)!=0)
{
fprintf(stderr,"__%d__",__LINE__);
return -1;
}
//上锁
pthread_mutex_lock(&mutex);
lseek(word_r,0,SEEK_SET);
lseek(word_w,0,SEEK_SET);
char c = 0;
for(int i = 0;i<size;i++)
{
read(word_r,&c,1);
write(word_w,&c,1);
}
printf("前半部分打印完毕\n");
//解锁
pthread_mutex_unlock(&mutex);
//阻塞等待子线程结束
pthread_join(tid,NULL);
//关闭文件
close(word_r);
close(word_w);
//消除互斥锁
pthread_mutex_destroy(&mutex);
return 0;
}
思维导图