题目:
用两个线程拷贝一张图片,要求A线程拷贝前半部分,B线程拷贝后半部分;
提示:找到临界资源,临界区,上锁解锁即可;
代码:
#include <stdio.h>
#include <pthread.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
struct info
{
int fd_r;
int fd_w;
off_t size;
};
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void* callBack_front(void* arg)
{
int fd_r = ((struct info*)arg)->fd_r;
int fd_w = ((struct info*)arg)->fd_w;
off_t size = ((struct info*)arg)->size;
off_t offset = 0;
/********临界区*****/
char c = 0;
for(int i=0; i<size/2; i++)
{
pthread_mutex_lock(&mutex);
lseek(fd_r, offset, SEEK_SET);
lseek(fd_w, offset, SEEK_SET);
read(fd_r, &c, 1);
write(fd_w, &c, 1);
offset = lseek(fd_r, 0, SEEK_CUR);
pthread_mutex_unlock(&mutex);
}
/********临界区*****/
printf("前半部分拷贝完毕\n");
pthread_exit(NULL);
}
void* callBack_end(void* arg)
{
int fd_r = ((struct info*)arg)->fd_r;
int fd_w = ((struct info*)arg)->fd_w;
off_t size = ((struct info*)arg)->size;
char flag = size%2==1? 1:0;
off_t offset = size/2;
/********临界区*****/
char c = 0;
for(int i=0; i<size/2; i++)
{
pthread_mutex_lock(&mutex);
lseek(fd_r, offset, SEEK_SET);
lseek(fd_w, offset, SEEK_SET);
read(fd_r, &c, 1);
write(fd_w, &c, 1);
offset = lseek(fd_r, 0, SEEK_CUR);
pthread_mutex_unlock(&mutex);
}
/********临界区*****/
printf("后半部分拷贝完毕\n");
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
//打开两个文件
int fd_r = open(argv[1], O_RDONLY);
if(fd_r < 0)
{
perror("open");
return -1;
}
int fd_w = open(argv[2], O_WRONLY|O_CREAT|O_TRUNC, 0664);
if(fd_w < 0)
{
perror("open");
return -1;
}
off_t size = lseek(fd_r, 0, SEEK_END);
printf("size = %ld\n", size);
struct info msg;
msg.fd_r = fd_r;
msg.fd_w = fd_w;
msg.size = size;
pthread_t tid1, tid2;
if(pthread_create(&tid1, NULL, callBack_front, &msg) != 0)
{
fprintf(stderr, "pthread_create failed __%d__\n", __LINE__);
return -1;
}
if(pthread_create(&tid2, NULL, callBack_end, &msg) != 0)
{
fprintf(stderr, "pthread_create failed __%d__\n", __LINE__);
return -1;
}
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
close(fd_r);
close(fd_w);
pthread_mutex_destroy(&mutex);
return 0;
}
运行结果:
ubuntu@ubuntu:12.9$ ./a.out a0be0d9cb07fef8959db3e47acae1c79.jpeg b.c
size = 186176
前半部分拷贝完毕
后半部分拷贝完毕
ubuntu@ubuntu:12.9$ diff a0be0d9cb07fef8959db3e47acae1c79.jpeg b.c