Skip to content

Instantly share code, notes, and snippets.

@crsaracco
Created December 15, 2019 06:45
Show Gist options
  • Save crsaracco/d8c8c0ecc1a4c042f9a6d4b45b818b9f to your computer and use it in GitHub Desktop.
Save crsaracco/d8c8c0ecc1a4c042f9a6d4b45b818b9f to your computer and use it in GitHub Desktop.
crossbeam_channel allocation test
use std::alloc::{System, GlobalAlloc, Layout};
use std::sync::atomic::{AtomicUsize, Ordering::SeqCst, AtomicBool};
use std::sync::{Arc, Condvar, Mutex};
use std::thread;
use crossbeam_channel::bounded;
struct Allocator;
static ALLOCATIONS: AtomicUsize = AtomicUsize::new(0);
unsafe impl GlobalAlloc for Allocator {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
let ret = System.alloc(layout);
if !ret.is_null() {
ALLOCATIONS.fetch_add(1, SeqCst);
}
return ret;
}
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
System.dealloc(ptr, layout);
}
}
#[global_allocator]
static A: Allocator = Allocator;
fn main() {
let (tx, rx) = bounded(1_000_000);
// SENDER THREAD
let t1 = thread::spawn(move || {
loop {
let allocations_before = ALLOCATIONS.load(SeqCst);
tx.send(5);
let allocations_after = ALLOCATIONS.load(SeqCst);
println!("SENDER THREAD | before: {}, after: {}",
allocations_before, allocations_after);
}
});
// RECEIVER THREAD
let t2 = thread::spawn(move || {
loop {
let allocations_before = ALLOCATIONS.load(SeqCst);
let value = rx.recv().unwrap();
let allocations_after = ALLOCATIONS.load(SeqCst);
println!("RECEIVER THREAD | before: {}, after: {}, value: {}",
allocations_before, allocations_after, value);
}
});
t1.join();
t2.join();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment