Skip to content

Instantly share code, notes, and snippets.

@Irfy
Created March 6, 2012 02:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Irfy/1982902 to your computer and use it in GitHub Desktop.
Save Irfy/1982902 to your computer and use it in GitHub Desktop.
#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