用两个线程拷贝一张图片,要求A线程拷贝前半部分,B线程拷贝后半部分;提示:找到临界资源,临界区,上锁解锁即可;

代码如下:

#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <pthread.h>

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

struct info
{
    int fp;
    int fp1;
    off_t size;
};


void* A(void* arg)     
{

    int fp = ((struct info*)arg)->fp;
    int fp1= ((struct info*)arg)->fp1;
    off_t size = ((struct info*)arg)->size;

    /********临界区*******/
    pthread_mutex_lock(&mutex);
    lseek(fp, 0, SEEK_SET);
    lseek(fp1, 0, SEEK_SET);

    char c = 0;
    for(int i=0; i<size/2; i++)
    {
        read(fp, &c, 1);
        write(fp1, &c, 1);
    }
    pthread_mutex_unlock(&mutex);
    /********临界区*******/

    printf("前半部分拷贝完毕\n");
    pthread_exit(NULL);
}

void* B(void* arg)
{
    int fp= ((struct info*)arg)->fp;
    int fp1= ((struct info*)arg)->fp1;
    off_t size = ((struct info*)arg)->size;
    char flag = size%2==1? 1:0;

    /********临界区*******/
    pthread_mutex_lock(&mutex);
    lseek(fp, size/2, SEEK_SET);
    lseek(fp1, size/2, SEEK_SET);


    char c = 0;
    for(int i=0; i<size/2+flag; i++)
    {
        read(fp, &c, 1);
        write(fp1, &c, 1);
    }
    pthread_mutex_unlock(&mutex);
    /********临界区*******/

    printf("后半部分拷贝完毕\n");
    pthread_exit(NULL);

}

int main(int argc, const char *argv[])
{
    int fp= open("1.png", O_RDONLY);
    if(fp< 0)
    {
        perror("open");
        return -1;
    }
    int fp1= open("2.png", O_WRONLY|O_CREAT|O_TRUNC, 0664);
    if(fp1< 0)
    {
        perror("open");
        return -1;
    }

    off_t size = lseek(fp, 0, SEEK_END);

    struct info msg;
    msg.fp = fp;
    msg.fp1 = fp1;
    msg.size = size;

    pthread_t tid1, tid2;
    if(pthread_create(&tid1, NULL, A, &msg) != 0)
    {
        fprintf(stderr, "pthread_create failed\n");
        return -1;
    }

    if(pthread_create(&tid2, NULL,B, &msg) != 0)
    {
        fprintf(stderr, "pthread_create failed\n");
        return -1;
    }

    pthread_join(tid1, NULL);
    pthread_join(tid2, NULL);

    close(fp);
    close(fp1);

    pthread_mutex_destroy(&mutex);
    return 0;
}

结果如下:

ubuntu@ubuntu:day6$ gcc 5cp图片.c -pthread
ubuntu@ubuntu:day6$ ./a.out
后半部分拷贝完毕
前半部分拷贝完毕
ubuntu@ubuntu:day6$ diff 1.png 2.png
ubuntu@ubuntu:day6$ 
ubuntu@ubuntu:day6$ ls -l
总用量 1960
-rwxrw-rw- 1 ubuntu ubuntu 975234 十二  7 11:44 1.png
-rw-r--r-- 1 ubuntu ubuntu 975234 十二 12 20:26 2.png
-rw-r--r-- 1 ubuntu ubuntu   1727 十二 12 18:43 4cp图片.c
-rw-r--r-- 1 ubuntu ubuntu   2150 十二 12 18:57 5cp图片.c
-rwxr-xr-x 1 ubuntu ubuntu  13184 十二 12 20:26 a.out
ubuntu@ubuntu:day6$ 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值