Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix "illegal hardware instruction" in ch6-particles on MacOS #106

Open
wants to merge 2 commits into
base: 1st-edition
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 22 additions & 1 deletion ch6/ch6-particles/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,33 @@ 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.
/// Source: https://github.com/andrewhickman/logging-allocator/blob/master/src/lib.rs#L42-L57
pub fn run_guarded<F>(f: F)
where
F: FnOnce(),
{
thread_local! {
static GUARD: Cell<bool> = 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 {
Expand All @@ -22,7 +43,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
}

Expand Down