• thread互斥测试


    编译运行附件中的代码,并说明程序的功能
    根据自己的理解,提交不少于3张

     

    代码: 

    #include <stdio.h>
    #include <stdlib.h>
    #include <pthread.h>
    #include <ctype.h>

    struct arg_set {
    char *fname;
    int count;
    };

    struct arg_set *mailbox = NULL;
    pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
    pthread_cond_t flag = PTHREAD_COND_INITIALIZER;

    void *count_words(void *);
    int main(int argc, char *argv[])
    {
    pthread_t t1, t2;
    struct arg_set args1, args2;
    int reports_in = 0;
    int total_words = 0;

    if ( argc != 3 ){
    printf("usage: %s file1 file2 ", argv[0]);
    exit(1);
    }

    args1.fname = argv[1];
    args1.count = 0;
    pthread_create(&t1, NULL, count_words, (void *) &args1);

    args2.fname = argv[2];
    args2.count = 0;
    pthread_create(&t2, NULL, count_words, (void *) &args2);

    pthread_mutex_lock(&lock);
    while( reports_in < 2 ){
    printf("MAIN: waiting for flag to go up ");
    pthread_cond_wait(&flag, &lock);
    printf("MAIN: Wow! flag was raised, I have the lock ");
    printf("%7d: %s ", mailbox->count, mailbox->fname);
    total_words += mailbox->count;
    if ( mailbox == &args1)
    pthread_join(t1,NULL);
    if ( mailbox == &args2)
    pthread_join(t2,NULL);
    mailbox = NULL;
    pthread_cond_signal(&flag);
    reports_in++;
    }
    pthread_mutex_unlock(&lock);

    printf("%7d: total words ", total_words);
    }
    void *count_words(void *a)
    {
    struct arg_set *args = a;
    FILE *fp;
    int c, prevc = '';

    if ( (fp = fopen(args->fname, "r")) != NULL ){
    while( ( c = getc(fp)) != EOF ){
    if ( !isalnum(c) && isalnum(prevc) )
    args->count++;
    prevc = c;
    }
    fclose(fp);
    } else
    perror(args->fname);
    printf("COUNT: waiting to get lock ");
    pthread_mutex_lock(&lock);
    printf("COUNT: have lock, storing data ");
    if ( mailbox != NULL ){
    printf("COUNT: oops..mailbox not empty. wait for signal ");
    pthread_cond_wait(&flag,&lock);
    }
    mailbox = args;
    printf("COUNT: raising flag ");
    pthread_cond_signal(&flag);
    printf("COUNT: unlocking box ");
    pthread_mutex_unlock(&lock);
    return NULL;
    }

     

  • 相关阅读:
    HDU 4972 A simple dynamic programming problem
    dd usb 启动盘制作 成功版本
    1233
    openstack kvm 虚拟机磁盘差异衍生
    怎样安装g++/gdb
    区间最小值 线段树 (2015年 JXNU_ACS 算法组暑假第一次周赛)
    hdu
    TCP/IP解析(一):TCP/IP的工作方式
    使用Python生成源文件的两种方法
    zoj1003 Crashing Balloon
  • 原文地址:https://www.cnblogs.com/lxhs/p/15555196.html
Copyright © 2020-2023  润新知