线程互斥量

来源:互联网 发布:歌词中的励志句子知乎 编辑:程序博客网 时间:2024/05/21 12:40

测试完成一道题

(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
原创粉丝点击