@@ -4,41 +4,46 @@ pub mod arc_swap;
44#[ cfg( feature = "rwlock" ) ]
55pub mod rw_lock;
66
7- #[ cfg( test) ]
87mod allocation_tests {
8+ use super :: * ;
99 use std:: alloc:: { GlobalAlloc , Layout , System } ;
10- use std:: cell:: Cell ;
10+ use std:: sync:: atomic:: { AtomicUsize , Ordering } ;
11+ use std:: sync:: { RwLock , RwLockWriteGuard } ;
1112
12- struct CountingAlloc ;
13-
14- #[ global_allocator]
15- static GLOBAL : CountingAlloc = CountingAlloc ;
16-
17- thread_local ! {
18- // Each OS thread gets its own counter.
19- static ALLOCS_THIS_THREAD : Cell <usize > = const { Cell :: new( 0 ) } ;
13+ struct CountingAlloc {
14+ inner : System ,
15+ allocs : RwLock < usize > ,
2016 }
2117
2218 unsafe impl GlobalAlloc for CountingAlloc {
2319 unsafe fn alloc ( & self , layout : Layout ) -> * mut u8 {
24- let ptr = unsafe { System . alloc ( layout) } ;
25- if !ptr. is_null ( ) {
26- // Only bump the counter for the *current* thread.
27- ALLOCS_THIS_THREAD . with ( |c| c. set ( c. get ( ) + 1 ) ) ;
20+ let ptr = self . inner . alloc ( layout) ;
21+ if let Ok ( mut guard) = self . allocs . try_write ( ) {
22+ * guard += 1 ;
2823 }
2924 ptr
3025 }
3126
3227 unsafe fn dealloc ( & self , ptr : * mut u8 , layout : Layout ) {
33- unsafe { System . dealloc ( ptr, layout) } ;
28+ self . inner . dealloc ( ptr, layout) ;
3429 }
3530 }
3631
37- pub ( crate ) fn reset_allocs_current_thread ( ) {
38- ALLOCS_THIS_THREAD . with ( |c| c. set ( 0 ) ) ;
32+ #[ global_allocator]
33+ static GLOBAL : CountingAlloc = CountingAlloc {
34+ inner : System ,
35+ allocs : RwLock :: new ( 0 ) ,
36+ } ;
37+
38+ pub ( crate ) fn reset_allocs ( ) -> RwLockWriteGuard < ' static , usize > {
39+ let mut guard = GLOBAL . allocs . write ( ) . unwrap ( ) ;
40+ * guard=0 ;
41+ guard
3942 }
4043
41- pub ( crate ) fn allocs_current_thread ( ) -> usize {
42- ALLOCS_THIS_THREAD . with ( |c| c. get ( ) )
44+ pub ( crate ) fn allocs ( guard : RwLockWriteGuard < ' static , usize > ) -> usize {
45+ let mut allocs = * guard;
46+ drop ( guard) ;
47+ allocs
4348 }
44- }
49+ }
0 commit comments