I am writing a program that prints out fibonacci numbers. When I tried to implement threading, the program will crash (normally while printing a number, not calculating the next) with the sole message Killed. I have ran dstat --top-oom and my program never shows up (rust-analyzer sits at 754 and does not move when running the program).
Code:
use rug::Integer;
use std::sync::mpsc;
use std::thread;
struct FibSequ {
curr: Integer,
next: Integer
}
impl Default for FibSequ {
fn default() -> Self {
Self {curr: Integer::from(0), next: Integer::from(1)}
}
}
impl Iterator for FibSequ {
type Item = Integer;
fn next(&mut self) -> Option<Self::Item> {
let current = self.curr.clone();
self.curr = self.next.clone();
self.next = ¤t + self.next.clone();
Some(current)
}
}
fn main() {
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
let mut fib = FibSequ::default();
loop {
tx.send(fib.next().unwrap()).unwrap();
}
});
for i in rx {
println!("{}", i);
}
}
Bin: Bin [md5: 07e3d09f41e1153694ef4e041c7eeb50]
Last bit of output before it crashed:
...7680751160335033301153281304688311853222415855824651640807481Killed
You are using an unbounded channel, which means it is infinitely buffered. Writing the numbers to the terminal is much slower than computing new numbers, so your channel will buffer an increasing amount of numbers. The easiest way to fix this is using a bounded channel instead. All you need to do is replacing
mpsc::channel()with something likempsc::sync_channel(10), allowing for a queue of ten numbers. The program will still eventually oom, but it takes way longer.On my Ubuntu box the process gets terminated by earlyoom. Since earlyoom is sending SIGTERM, I see
Terminatedinstead ofKilled. The event is logged in the syslog: