Skip to main content

preallocating/
preallocating.rs

1//! Demonstrates eager per-thread queue allocation with `preallocate_thread`.
2
3use std::{error::Error, sync::Arc, thread};
4
5use insomnilog::{
6    BackendOptions, ConsoleSink, LogLevel, PatternFormatter, create_logger, log_info,
7    preallocate_thread, start,
8};
9
10fn main() -> Result<(), Box<dyn Error>> {
11    let _guard = start(BackendOptions::default())?;
12
13    let sink: Arc<dyn insomnilog::Sink> = Arc::new(ConsoleSink::new(
14        PatternFormatter::default(),
15        LogLevel::Info,
16    ));
17    let logger = create_logger("app", vec![sink], LogLevel::Info)?;
18
19    // ANCHOR: main_thread
20    // Allocate the queue for the main thread before entering the hot path.
21    preallocate_thread();
22    // ANCHOR_END: main_thread
23
24    log_info!(logger, "main thread ready");
25
26    // ANCHOR: worker_thread
27    let worker_logger = Arc::clone(&logger);
28    thread::spawn(move || {
29        // Allocate the queue for this thread before any log call.
30        preallocate_thread();
31
32        log_info!(worker_logger, "worker thread ready");
33    })
34    .join()
35    .unwrap();
36    // ANCHOR_END: worker_thread
37
38    Ok(())
39}