非阻塞输入C [英] Non blocking input C
问题描述
我正在尝试创建一个程序,向用户询问一个问题并有几秒钟的时间回答该问题,否则该程序将停止输入.
I'm trying to create a program where the user is asked a question and has a few seconds to answer the question, or else the program stops input.
现在我的问题是我无法使我的程序不阻止输入. 我可以输入数据,但是当我不输入数据并且计时器用完时,它会不断要求输入.
Now my problem is I'm unable to get my program not to block input. I am able to input data, but when I don't and the timer runs out it keeps asking for input.
我正在Windows上运行,并使用Code :: Blocks以防万一. 如果有人可以向我解释我在做什么错,那将不胜感激.
I'm running on Windows and use Code::Blocks in case it's important. If someone could explain to me what I'm doing wrong, it would be appreciated.
#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;
}
推荐答案
当时间用完时,请timeleft()
设置一个全局标志,该标志由questions()
测试,如果设置,则使代码离开while (1)
循环.
When time ran out have timeleft()
set a global flag, which is tested by questions()
, and if set makes the code leave the while (1)
loop.
确保使用互斥锁保护对标志的访问.
Make sure access to the flag is protected using a mutex.
谈论受保护的访问":key
是在没有保护的情况下并发访问的.不好.
Talking about "protected access": key
is accessed concurrently without protection. Not good.
这篇关于非阻塞输入C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!