Skip to content

Commit

Permalink
fix: don't attempt to reuse in foreground thread
Browse files Browse the repository at this point in the history
Signed-off-by: andylokandy <[email protected]>
  • Loading branch information
andylokandy committed Jun 21, 2024
1 parent e30a0ae commit 734e365
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 2 deletions.
1 change: 1 addition & 0 deletions minitrace/benches/object_pool.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ fn bench_alloc_vec(c: &mut Criterion) {
for cap in &[1, 10, 100, 1000, 10000, 100000] {
let vec_pool: Pool<Vec<usize>> = Pool::new(Vec::new, Vec::clear);
let mut puller = vec_pool.puller(512);
minitrace::util::object_pool::enable_reuse_in_current_thread();
bgroup.bench_function(format!("object-pool/{}", cap), |b| {
b.iter_batched(
|| (),
Expand Down
3 changes: 3 additions & 0 deletions minitrace/src/collector/global_collector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ use crate::collector::SpanSet;
use crate::collector::TraceId;
use crate::local::local_collector::LocalSpansInner;
use crate::local::raw_span::RawSpan;
use crate::util::object_pool;
use crate::util::spsc::Receiver;
use crate::util::spsc::Sender;
use crate::util::spsc::{self};
Expand Down Expand Up @@ -252,6 +253,8 @@ impl GlobalCollector {
}

fn handle_commands(&mut self, flush: bool) {
object_pool::enable_reuse_in_current_thread();

debug_assert!(self.start_collects.is_empty());
debug_assert!(self.drop_collects.is_empty());
debug_assert!(self.commit_collects.is_empty());
Expand Down
22 changes: 20 additions & 2 deletions minitrace/src/util/object_pool.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,28 @@
// Copyright 2022 TiKV Project Authors. Licensed under Apache-2.0.

use std::cell::Cell;
use std::mem::ManuallyDrop;
use std::ops::Deref;
use std::ops::DerefMut;

use parking_lot::Mutex;

thread_local! {
static REUSABLE: Cell<bool> = Cell::new(false);
}

pub fn enable_reuse_in_current_thread() {
REUSABLE.with(|r| r.set(true));
}

fn is_reusable() -> bool {
REUSABLE.with(|r| r.get())
}

pub struct Pool<T> {
// The objects in the pool ready to be reused.
// The mutex should only be visited in the global collector, which is guaranteed by `is_reusable`,
// so it should not have synchronization overhead.
objects: Mutex<Vec<T>>,
init: fn() -> T,
reset: fn(&mut T),
Expand Down Expand Up @@ -46,8 +62,10 @@ impl<T> Pool<T> {

#[inline]
pub fn recycle(&self, mut obj: T) {
(self.reset)(&mut obj);
self.objects.lock().push(obj)
if is_reusable() {
(self.reset)(&mut obj);
self.objects.lock().push(obj)
}
}
}

Expand Down

0 comments on commit 734e365

Please sign in to comment.