Created
March 6, 2012 02:12
-
-
Save Irfy/1982902 to your computer and use it in GitHub Desktop.
Working example for SO question 9575981 (http://stackoverflow.com/questions/9575981/how-to-put-a-time-limit-on-user-input/9576051)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <vector> | |
#include <cstdio> | |
#include <unistd.h> | |
#include <pthread.h> | |
#include <termios.h> | |
using std::cout; | |
using std::getchar; | |
pthread_mutex_t qlock; | |
std::vector<char> queue; | |
inline void lock_queue() { | |
pthread_mutex_lock(&qlock); // XXX handle rv | |
} | |
inline void unlock_queue() { | |
pthread_mutex_unlock(&qlock); // XXX handle rv | |
} | |
#define DEFAULT_ACTION ' ' | |
#define TERMINATE_ACTION 'q' | |
void perform_action(char action) { | |
// magic processing... | |
cout << action; | |
} | |
void* action_processor(void *) { | |
char action; | |
cout << "Starting timed processing loop...\n"; | |
do { | |
usleep(1000000); | |
lock_queue(); | |
if (queue.size() == 0) { | |
action = DEFAULT_ACTION; | |
} else { | |
// either handle multiple key events somehow | |
// or use the last key event: | |
action = queue.back(); | |
queue.clear(); | |
} | |
unlock_queue(); | |
perform_action(action); | |
} while (action != TERMINATE_ACTION); | |
cout << "\nExiting timed processing loop...\n"; | |
pthread_exit(NULL); | |
return NULL; | |
} | |
void input_loop() { | |
cout << "Starting input loop...\n"; | |
struct termios term; | |
tcgetattr(0, &term); | |
cfmakeraw(&term); | |
tcsetattr(0, TCSAFLUSH, &term); | |
char input; | |
do { | |
input = (char) getchar(); // XXX handle EOF | |
lock_queue(); | |
queue.push_back(input); | |
unlock_queue(); | |
} while (input != TERMINATE_ACTION); | |
cout << "\nExiting input loop...\n"; | |
} | |
int main(int argc, char *argv[]) { | |
pthread_t thread; | |
pthread_create(&thread, NULL, action_processor, NULL); // XXX handle rv | |
input_loop(); | |
pthread_exit(NULL); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment