From a0731bc66504fdd74f4d548059cb6ad2fb34539a Mon Sep 17 00:00:00 2001 From: Christian Koopmann Date: Mon, 30 Jan 2023 12:00:24 +0800 Subject: [PATCH 1/2] Wrap eprintln in run_guarded function --- ch6/ch6-particles/src/main.rs | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/ch6/ch6-particles/src/main.rs b/ch6/ch6-particles/src/main.rs index 212ebb49..ed547885 100644 --- a/ch6/ch6-particles/src/main.rs +++ b/ch6/ch6-particles/src/main.rs @@ -7,12 +7,32 @@ use rand::prelude::*; // <3> use std::alloc::{GlobalAlloc, System, Layout}; // <4> use std::time::Instant; // <5> + // +use std::cell::Cell; #[global_allocator] // <6> static ALLOCATOR: ReportingAllocator = ReportingAllocator; struct ReportingAllocator; // <7> + // + // +/// Execute a closure without logging on allocations. +pub fn run_guarded(f: F) +where + F: FnOnce(), +{ + thread_local! { + static GUARD: Cell = Cell::new(false); + } + + GUARD.with(|guard| { + if !guard.replace(true) { + f(); + guard.set(false) + } + }) +} unsafe impl GlobalAlloc for ReportingAllocator { unsafe fn alloc(&self, layout: Layout) -> *mut u8 { @@ -22,7 +42,7 @@ unsafe impl GlobalAlloc for ReportingAllocator { let time_taken = end - start; let bytes_requested = layout.size(); - eprintln!("{}\t{}", bytes_requested, time_taken.as_nanos()); + run_guarded(|| {eprintln!("{}\t{}", bytes_requested, time_taken.as_nanos())}); ptr } From ee850071c955ce2d8073c7fe1fd76d17b7db219a Mon Sep 17 00:00:00 2001 From: Christian Koopmann Date: Mon, 30 Jan 2023 12:07:16 +0800 Subject: [PATCH 2/2] Add reference to source for run_guarded function --- ch6/ch6-particles/src/main.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/ch6/ch6-particles/src/main.rs b/ch6/ch6-particles/src/main.rs index ed547885..f5f5a9c2 100644 --- a/ch6/ch6-particles/src/main.rs +++ b/ch6/ch6-particles/src/main.rs @@ -18,6 +18,7 @@ struct ReportingAllocator; // <7> // // /// Execute a closure without logging on allocations. +/// Source: https://github.com/andrewhickman/logging-allocator/blob/master/src/lib.rs#L42-L57 pub fn run_guarded(f: F) where F: FnOnce(),