作业
创建两个线程:其中一个线程拷贝前半部分,另一个线程拷贝后半部分。
只允许开一份资源,且用互斥锁方式实现。 提示:找临界区---》找临界资源。
代码
#include <stdio.h>
#include <head.h>
struct Msg
{
int fd_r;
int fd_w;
off_t size;
};
pthread_mutex_t mutex;
void *callBack1(void *arg)
{
int fd_r = ((struct Msg*)arg) -> fd_r;
int fd_w = ((struct Msg*)arg) -> fd_w;
off_t size = ((struct Msg*)arg) -> size;
char c = 0;
pthread_mutex_lock(&mutex);
lseek(fd_r, 0, SEEK_SET);
lseek(fd_w, 0, SEEK_SET);
for (int i = 0; i < size / 2; i++)
{
read(fd_r, &c, 1);
write(fd_w, &c, 1);
}
printf("上半部分拷贝完毕\n");
pthread_mutex_unlock(&mutex);
printf("线程1准备退出\n");
pthread_exit(NULL);
return NULL;
}
void *callBack2(void *arg)
{
int fd_r = ((struct Msg*)arg) -> fd_r;
int fd_w = ((struct Msg*)arg) -> fd_w;
off_t size = ((struct Msg*)arg) -> size;
char c = 0;
pthread_mutex_lock(&mutex);
lseek(fd_r, size / 2, SEEK_SET);
lseek(fd_w, size / 2, SEEK_SET);
for (int i = size / 2; i < size; i++)
{
read(fd_r, &c, 1);
write(fd_w, &c, 1);
}
printf("下半部分拷贝完毕\n");
pthread_mutex_unlock(&mutex);
printf("线程2准备退出\n");
pthread_exit(NULL);
return NULL;
}
int main(int argc, const char *argv[])
{
pthread_mutex_init(&mutex, NULL);
printf("<---若出现拷贝完毕提示,可以按回车结束该程序--->\n");
//pthread_mutex_lock(&mutex);
int fd_r = open("./1.png", O_RDONLY);
if (fd_r < 0)
{
ERR_MSG("open");
return -1;
}
int fd_w = open("copy1.png", O_WRONLY | O_CREAT | O_TRUNC, 0664);
if (fd_w < 0)
{
ERR_MSG("open");
return -1;
}
off_t size = lseek(fd_r, 0, SEEK_END);
struct Msg filemsg = {fd_r, fd_w, size};
pthread_t tid1, tid2;
if (pthread_create(&tid1, NULL, callBack1, &filemsg) != 0)
{
fprintf(stderr, "pthread_create fail __%d__\n", __LINE__);
return -1;
}
//pthread_mutex_unlock(&mutex);
if (pthread_create(&tid2, NULL, callBack2, &filemsg) != 0)
{
fprintf(stderr, "pthread_create fail __%d__\n", __LINE__);
return -1;
}
//pthread_detach(tid2);
// pthread_join(tid1, NULL);
// pthread_join(tid2, NULL);
//pthread_mutex_lock(&mutex);
//pthread_detach(tid1);
//pthread_mutex_unlock(&mutex);
//pthread_mutex_lock(&mutex);
//pthread_detach(tid2);
//pthread_mutex_unlock(&mutex);
char s;
s = getchar();
pthread_mutex_destroy(&mutex);
close(fd_r);
close(fd_w);
printf("文件拷贝完毕\n");
return 0;
}
截图
思维导图