甚至我的主要功能都没有运行

时间:2015-03-28 17:14:38

标签: c pthreads semaphore

我甚至无法打印" Main"屏幕上。好像我的代码都没有运行。当我没有指定任何命令行参数打印出警告。我的输入文件在每一行都包含整数。

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <semaphore.h>
#include <sys/types.h>

int patientCount,treatedPatientCount,maxPatient,allRegistered;
int *list;

FILE *input,*output;

sem_t semOutputFile,semGlobalVars;

void* Nurse();
void* Doctor(void *);

int main( int argc, char *argv[] ){
    printf("Main");

    if(argc != 3){
        printf("Command line argument count is different then expected. Aborting!");
        return -1;
    }

    input = fopen(argv[1],"r");
    output = fopen(argv[2],"w");

    allRegistered = 0;
    maxPatient = 5;
    treatedPatientCount = 0;
    patientCount = 0;
    list = malloc(sizeof(int)*maxPatient);

    pthread_t nurse,doc1,doc2;
    sem_init(&semGlobalVars, 0, 1);
    sem_init(&semOutputFile, 0, 1);

    pthread_create(&nurse, NULL, &Nurse, NULL);
    pthread_create(&doc1, NULL, &Doctor, (void*) 1);
    pthread_create(&doc2, NULL, &Doctor, (void*) 2);

    pthread_exit(NULL);
}

void* Nurse(){

    char buff[255],*eof;
    while(1){
        eof = fgets(buff, 255, input);
        if (eof == NULL) {
            allRegistered = 1;
            pthread_exit(NULL);
        }
        int k = atoi(buff);

        sem_wait(&semGlobalVars);//Critical region 1 starts
        if(patientCount == maxPatient){
            maxPatient *=2;
            list = realloc(list,sizeof(int)*maxPatient);
        }
        list[patientCount++] = k;
        sem_post(&semGlobalVars);//Critical region 1 ends

        sem_wait(&semOutputFile);//Critical region 2 starts
        fputs("Nurse registered a patient!\n",output);
        sem_post(&semOutputFile);//Critical region 2 ends

        sleep(2);
    }
}

void* Doctor(void * id){
    printf("Doctor");
    char buff[255];
    int waitTime = 0;
    while(1){
        printf("%d %d %d",allRegistered,treatedPatientCount,patientCount);
        if(allRegistered == 1 && treatedPatientCount==patientCount) pthread_exit(NULL);
        sem_wait(&semGlobalVars);//Critical region 1 starts
        waitTime = list[treatedPatientCount++];
        sem_post(&semGlobalVars);//Critical region 1 ends

        sprintf (buff, "Doctor %d treated a patient\n", (int) id);
        sem_wait(&semOutputFile);//Critical region 2 starts
        fputs(buff,output);
        sem_post(&semOutputFile);//Critical region 2 ends

        sleep(waitTime);
    }
}

1 个答案:

答案 0 :(得分:1)

您可以将exit(0)添加到main

的末尾

exit(0)做的是刷新所有缓冲区(以及其他好东西),确保所有缓冲的内容(如#34; Main&#34;的printf)被写出来。

All C streams (open with functions in <cstdio>) are closed (and flushed, if buffered), and all files created with tmpfile are removed.

http://www.cplusplus.com/reference/cstdlib/exit/