gpt4 book ai didi

c - 甚至我的主要功能也没有运行

转载 作者:行者123 更新时间:2023-11-30 15:22:09 25 4
gpt4 key购买 nike

我什至无法在屏幕上打印“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);
}
}

最佳答案

您可以添加exit(0)main结束

什么exit(0)所做的是刷新所有缓冲区(以及其他好事),确保缓冲的任何内容(例如“Main”的 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/

关于c - 甚至我的主要功能也没有运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29320104/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com