I am working on a basic project. I have progressed a lot (first time). And I have encountered an obstacle while trying to make this as a working application.
What I mean by that is, it has a main loop which is infinite. The program will run until user presses q. By the way, the program is console application. And I'm working on Linux.
While the program is working, it needs to do some operation foo in intervals (eg. 1 hour, 30 minutes, 4 hours).
And yes that's it. I know it doesn't sound complicated but I'm stuck. So what I want is, a Stdin which waits for user input without blocking the application and during that time do foo for each 1 hour (let's stick with one hour). But between these foos, I don't want my program spin constantly. Because that causes 100% CPU usage. I want my program work when there is a need for work (eg. When elapsed time is 1 hour or When user presses q).
I used a library for manipulating the terminal. And that library has a feature for Stdin without blocking. And I looked it's implementation I saw that it creates another thread to handle this. Since I have to do other feature on my own. I need some help to figure it out.
For elapsing the time without spinning. I tried sleep main thread. It did help but it made user input not responsive. If the user presses q while main thread is sleeping. It waits for it to wake up. I don't want this. I want it to quit immediately if it is idle. (not doing foo). if it is doing foo, quit after foo is done. By the way foo is not a heavy computation in my code.
fn foo() {
println!("bar");
}
fn main() {
let mut instant = Instant::now();
let one_hour = Duration::from_secs(60 * 60);
let mut stdin = async_stdin().bytes();
loop {
// No need to work
std::thread::sleep(one_hour);
// Just to be sure
if instant.elapsed() > one_hour {
foo();
instant = Instant::now();
}
// Check for input if there is any
match stdin.next() {
Some(Ok(b'q')) => break,
_ => (),
}
}
}
foo stdin foo stdin
| | | |
| | | | <- Press q
| | | |
| | <- exit here
|<- Press q and or |
| exit immediately |
| |
| |
| |
| |
I use Rust for my project but pseudocode is fine to me. I am very new to concepts of multithreading and asynchronous. I know they are not the same. I don't even know which is needed for this. Which synchronization objects do I need? Any tips, references, links will help.