线程互斥量

测试完成一道题

(google面试题)
有四个线程1、2、3、4。线程1的功能就是输出1,线程2的功能就是输出2,以此类推………现在有四个文件ABCD。初始都为空。现要让四个文件呈如下格式:

A:1 2 3 4 1 2….

B:2 3 4 1 2 3….

C:3 4 1 2 3 4….

D:4 1 2 3 4 1….

请设计程序。

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


struct pass_arg {
    int print_num;
    int file_descriptor[4];
};

pthread_mutex_t file_lock[4] = {
    PTHREAD_MUTEX_INITIALIZER,      /* A file lock */
    PTHREAD_MUTEX_INITIALIZER,      /* B file lock */
    PTHREAD_MUTEX_INITIALIZER,      /* C file lock */
    PTHREAD_MUTEX_INITIALIZER       /* D file lock */
};

int who_write_file_flag[4] = {
    '1',
    '2',
    '3',
    '4'
};

int run = 1;    /* thread run flag 0: stop, not 0 run */

void *thread_body(void *arg)
{
    int i;
    struct pass_arg *argument = (struct pass_arg *)arg;

    while (1) {
        if (run) {
            for (i=0; i<4; i++) {
                if (who_write_file_flag[i] == argument->print_num) {
                    pthread_mutex_lock(&file_lock[i]);
                    write(argument->file_descriptor[i], (const void *)&argument->print_num, 1);
                    write(argument->file_descriptor[i], (const void *)" ", 1);
                    who_write_file_flag[i] += 1;
                    if (who_write_file_flag[i] == '5')
                        who_write_file_flag[i] = '1';
                    pthread_mutex_unlock(&file_lock[i]);
                }
            }
        }
    }
    return (void *)0;
}

int main(void)
{
    int fdA;
    int fdB;
    int fdC;
    int fdD;
    int i;
    pthread_t pthread_id[4];
    fdA = open("A", O_RDWR | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP);
    fdB = open("B", O_RDWR | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP);
    fdC = open("C", O_RDWR | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP);
    fdD = open("D", O_RDWR | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP);

    struct pass_arg arg[4];
    for (i=0; i<4; i++) {
        arg[i].print_num = i + '1';
        arg[i].file_descriptor[0] = fdA;
        arg[i].file_descriptor[1] = fdB;
        arg[i].file_descriptor[2] = fdC;
        arg[i].file_descriptor[3] = fdD;
    }

    for (i=0; i<4; i++) {
        pthread_create(&pthread_id[i], NULL, thread_body, (void *)&arg[i]);
    }

    sleep(10);
    run = 0;    /* stop thread */
    sleep(2);
    close(fdA);
    close(fdB);
    close(fdC);
    close(fdD);
    return 0;
}

可以完成。主线程没有判断子线程是否都退出,可以完善一下.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值