Edit: Bawh, ninja'd by Fernando :)
Okay, so I'm not 100% sure on what the best answer will be for you because I can't tell what you want your program to eventually do.
First and foremost, this is not the kind of problem that should be solved using threads. Threads are not the catch-all solution to everything and generally have huge overhead compared to other solutions. Because you're already using pthreads, I'll assume Windows compatibility isn't an issue.
The first step is to disable canonical mode, which will allow you to gett characters without having to wait for enter. If you were 100% sure stdin won't ever be a terminal, you can skip this step.
#include <iostream>
#include <termios.h>
void toggle_canonical(bool on) {
struct termios terminal_settings;
// Get the existing terminal settings
tcgetattr(0 /* stdin */, &terminal_settings);
if(on) {
// Disable canonical mode
terminal_settings.c_lflag &= ~ICANON;
// Read at least one character.
terminal_settings.c_cc[VMIN] = 1;
} else {
// Enable canonical mode
terminal_settings.c_lflag |= ICANON;
}
tcsetattr(0 /* stdin */, TCSANOW, &terminal_settings);
return;
}
int main(const int argc, const char* argv[]) {
// The read timeout, which can be 0 if you don't want to block at all.
struct timeval to = {5 /* seconds */, 0 /* miliseconds */};
fd_set read_fds;
int ret = 0;
// Turn canonical mode on
toggle_canonical(true);
FD_ZERO(&read_fds);
FD_SET(0, &read_fds);
// The first parameter to select() is the highest file
// descriptor in the set + 1, so in this case because
// STDIN == 0, we pass 1. This is actually completely
// ignored on several platforms, including Windows.
if((ret = select(1, &read_fds /* read set */, NULL /* write set */, NULL /* error set */, &to /* timeout */)) == 0) {
std::cout << "You didn't type anything in time." << std::endl;
} else if (ret == 1) {
std::cout << "Yay, you typed something in time!" << std::endl;
} else if (ret == -1) {
std::cout << "Oh no, an error occured!" << std::endl;
}
// Turn canonical mode off
toggle_canonical(false);
return 0;
}