Skip to content

Commit 92711e8

Browse files
committed
remove thread
1 parent 366ebed commit 92711e8

File tree

5 files changed

+35
-19
lines changed

5 files changed

+35
-19
lines changed

Cargo.lock

+1
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

+1
Original file line numberDiff line numberDiff line change
@@ -6,3 +6,4 @@ edition = "2021"
66
[dependencies]
77
termion = "1.5.6"
88
rand = "0.8.5"
9+
libc = "0.2.137"

perf.data

73.9 KB
Binary file not shown.

perf.data.old

237 KB
Binary file not shown.

src/main.rs

+33-19
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,11 @@
11
// Conways game of life
22

3+
extern crate libc;
4+
5+
use libc::{fcntl, F_GETFL, F_SETFL, O_NONBLOCK};
36
use std::io::Stdout;
47
use std::io::{stdout, Read, Write};
8+
use std::os::unix::io::AsRawFd;
59
use std::sync::mpsc;
610
use std::thread;
711
use termion::clear;
@@ -21,29 +25,36 @@ fn main() {
2125
let height = height as usize;
2226
let mut world = World::new(width, height);
2327

24-
let mut buffer = [0u8; 1];
25-
26-
let (tx, rx) = mpsc::channel();
27-
28-
let input_thread = thread::spawn(move || {
29-
loop {
30-
match stdin.read(&mut buffer) {
31-
Ok(0) => {} // No input available, continue the loop
32-
Ok(_) => {
33-
tx.send(buffer[0]).unwrap();
34-
}
35-
Err(e) => eprintln!("Error reading from stdin: {}", e),
36-
}
28+
// Set stdin to non-blocking
29+
unsafe {
30+
let fd = std::io::stdin().as_raw_fd();
31+
let flags = fcntl(fd, F_GETFL, 0);
32+
if flags != -1 {
33+
fcntl(fd, F_SETFL, flags | O_NONBLOCK);
3734
}
38-
});
35+
}
36+
37+
let mut buffer = [0u8; 1];
3938

4039
let mut on = false;
40+
let read_char_time = 100;
41+
let mut read_char_timer = 0;
42+
let mut read_char = true;
4143
world.randomize();
4244
home(width, height, &mut stdout);
4345
loop {
44-
match rx.try_recv() {
45-
Ok(input) => {
46-
match input {
46+
read_char_timer -= 1;
47+
if read_char_timer <= 0 {
48+
read_char = true;
49+
read_char_timer = read_char_time;
50+
}
51+
if read_char {
52+
match std::io::stdin().read(&mut buffer) {
53+
Ok(0) => {
54+
// std::thread::sleep(std::time::Duration::from_millis(100));
55+
}
56+
Ok(_) => {
57+
match buffer[0] {
4758
b'q' => break, // Exit the loop when 'q' is pressed.
4859
b'r' => world.randomize(), // Randomize the world when 'r' is pressed
4960
b' ' => on = !on, // Start/stop the world when 's' is pressed
@@ -53,9 +64,12 @@ fn main() {
5364
, // Home screen when 'h' is pressed
5465
_ => {} // Ignore other inputs
5566
}
67+
}
68+
Err(e) => {
69+
// eprintln!("Error reading from stdin: {}", e);
70+
// std::thread::sleep(std::time::Duration::from_millis(100));
71+
}
5672
}
57-
Err(mpsc::TryRecvError::Empty) => {} // No input available, continue the loop
58-
Err(mpsc::TryRecvError::Disconnected) => break, // Input thread has terminated, exit the loop
5973
}
6074

6175
// when user presses q, exit the loop

0 commit comments

Comments
 (0)