Hey there,
In the example bellow, the StdoutMessege
struct works as intended by itself, however if I wrap it in a OnceLock I doesn't actually print anything, even though the function print
gets called every time.
use std::{
fmt::Display,
io::{self, BufWriter, Stdout, Write},
sync::{Mutex, OnceLock},
thread,
};
static STDOUT_BUF: OnceLock<StdoutMessage> = OnceLock::new();
#[derive(Debug)]
struct StdoutMessage {
writer: Mutex<BufWriter<Stdout>>,
}
impl StdoutMessage {
fn new() -> Self {
Self {
writer: Mutex::new(BufWriter::new(io::stdout())),
}
}
fn print(&self, message: impl Display) {
let mut writer = self.writer.lock().unwrap();
writer.write_all(format!("{message}\n").as_bytes()).unwrap();
}
}
fn stdout_init() {
STDOUT_BUF.set(StdoutMessage::new()).unwrap();
}
fn stdout_print(message: impl Display) {
STDOUT_BUF.get().unwrap().print(message);
}
fn main() {
stdout_init();
thread::scope(|s| {
for id in 0..5 {
s.spawn(move || {
for n in 0..10 {
stdout_print(format!("message {n} from thread {id}"))
}
});
}
});
}