Created
December 15, 2019 06:45
-
-
Save crsaracco/d8c8c0ecc1a4c042f9a6d4b45b818b9f to your computer and use it in GitHub Desktop.
crossbeam_channel allocation test
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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