2017-12-29 64 views
0

사용자가 질문을하고 몇 초 내에 질문에 답하는 프로그램을 만들려고합니다. 그렇지 않으면 프로그램이 입력을 중지합니다.논 블로킹 입력 C

내 문제는 내 프로그램이 입력을 차단하지 못하게하는 것입니다. 데이터를 입력 할 수 있지만 입력하지 않으면 타이머가 끊어져 계속 입력을 요청합니다.

Windows에서 실행 중이며 Code :: Blocks를 사용하는 것이 중요합니다. 누군가 내가 잘못하고있는 것을 나에게 설명 할 수 있다면 그것은 인정 될 것이다. 시간이 timeleft()questions()에 따라 시험 할 때, 글로벌 플래그를 설정하고, 설정 코드를 만드는 경우 한 뛰쳐

#include <stdio.h> 
#include <stdlib.h> 
#include <time.h> 
#include <pthread.h> 
#include <conio.h> 

int key = 0; 
int GradeTotal = 0; 

//runs an empty loop every iteration F.E. for loop 
void timer(int seconds) 
{ 
    clock_t wait = (clock() + (seconds * CLOCKS_PER_SEC)); 
    while(clock() < wait){} 

} 

void timeleft() 
{ 
    int index; 

    for(index = 5; index >= 0; index--) 
    { 
     if(key != 0) 
     { 
      pthread_exit(timeleft); 
     } 

     timer(1); 

     if(index == 0) 
     { 
     printf("\n\nTime's up!"); 
     } 
    } 
} 

void questions() 
{ 
    int key; 

    printf("what is 1 + 1?\nAnswer: "); 

    while(1) 
    { 
     if(_kbhit()) 
     { 
      key = _getch(); 
      printf("%c",key); 
      break; 
     } 
    } 
    if(key == 50) 
    { 
     GradeTotal += 1; 
    } 
} 


int main() 
{ 
    pthread_t thread1,thread2; 

    int index; 
    int seconds = 0; 
    pthread_create(&thread1, NULL, questions, NULL); 
    pthread_create(&thread2, NULL, timeleft, NULL); 
    pthread_join(thread1, NULL); 
    pthread_join(thread2, NULL); 

    printf("\n\nGrade: %d",GradeTotal); 

    return 0; 
} 
+1

'while (clock() Stargateur

+0

질문 : https://stackoverflow.com/questions/28382962/wait-for-press-enter-in-c-inside-a-while-loop –

+0

다음을 사용하여 제안하십시오 :'select ()'에 타임 아웃 값을 지정하면'select()'를 호출 할 때 오류가 발생했는지, 시간 초과로 인한 것인지 아니면 stdin이 데이터로 준비되어 있는지 확인하십시오. 그것이 있기 때문에 별도의 스레드에 배치하십시오. – user3629249

답변

1

while (1) 루프를 둡니다.

뮤텍스를 사용하여 플래그에 대한 액세스가 보호되어 있는지 확인하십시오.

"보호 된 액세스"에 대해 말하기 : key은 보호없이 동시에 액세스됩니다. 안좋다.

+0

감사합니다. 당신이 제안한 것처럼 전역 변수 검사 인덱스의 상태로 작동하도록했습니다. – SpicyUsername

1

이 예제에서는 pthread의 기능을 사용하여 타이머를 설정하고 문제가 발생하면 스레드를 취소합니다.이 예제에서는 오류를 확인하지 않았습니다. 실제 응용 프로그램에서, 당신은 그것을해야합니다 :

#include <stdio.h> 
#include <pthread.h> 
#include <time.h> 

void *wrapper_handle_question(pthread_cond_t *cond) { 
    char buf[2048]; 
    size_t i = fread(buf, 1, sizeof buf - 1, stdin); 
    buf[i] = '\0'; 
    printf("%s", buf); 
    pthread_cond_broadcast(cond); 
    return NULL; 
} 

void *handle_question(void *arg) { return wrapper_handle_question(arg); } 

int main(void) { 
    pthread_cond_t cond = PTHREAD_COND_INITIALIZER; 
    pthread_t question; 
    pthread_create(&question, NULL, &handle_question, &cond); 

    struct timespec ts; 
    clock_gettime(CLOCK_REALTIME, &ts); 
    ts.tv_sec += 5; 

    pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; 
    pthread_mutex_lock(&mutex); 

    int rc = pthread_cond_timedwait(&cond, &mutex, &ts); 
    pthread_mutex_unlock(&mutex); 
    if (rc == 0) { 
    pthread_join(question, NULL); 
    } else { 
    pthread_cancel(question); 
    printf("timeout!\n"); 
    } 
} 
+1

까다로운 것 : POSIX는 * fread()가 취소 지점이 될 것을 요구하지 않습니다. – alk