Skip to content

Commit

Permalink
fix: lock contention on acquiring the arena stats (#1207)
Browse files Browse the repository at this point in the history
## Rationale
There is no need to acquire the write lock when fetch arena's stats.

## Detailed Changes
Use `RwLock` instead of `Mutex` to protect the core of the
`MonoIncArena` to avoid lock contention.

## Test Plan
Existing tests.
  • Loading branch information
ShiKaiWi authored Sep 11, 2023
1 parent be97733 commit cfaa105
Show file tree
Hide file tree
Showing 3 changed files with 7 additions and 13 deletions.
3 changes: 0 additions & 3 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion components/arena/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,3 @@ workspace = true
workspace = true

[dependencies]
parking_lot = "0.11.1"
16 changes: 7 additions & 9 deletions components/arena/src/mono_inc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,9 @@
use std::{
alloc::{alloc, dealloc, Layout},
ptr::NonNull,
sync::Arc,
sync::{Arc, RwLock},
};

use parking_lot::Mutex;

use crate::arena_trait::{Arena, BasicStats, Collector, CollectorRef};

/// The noop collector does nothing on alloc and free
Expand All @@ -39,13 +37,13 @@ const DEFAULT_ALIGN: usize = 8;
/// allocated memory as blocks.
#[derive(Clone)]
pub struct MonoIncArena {
core: Arc<Mutex<ArenaCore>>,
core: Arc<RwLock<ArenaCore>>,
}

impl MonoIncArena {
pub fn new(regular_block_size: usize) -> Self {
Self {
core: Arc::new(Mutex::new(ArenaCore::new(
core: Arc::new(RwLock::new(ArenaCore::new(
regular_block_size,
Arc::new(NoopCollector {}),
))),
Expand All @@ -54,7 +52,7 @@ impl MonoIncArena {

pub fn with_collector(regular_block_size: usize, collector: CollectorRef) -> Self {
Self {
core: Arc::new(Mutex::new(ArenaCore::new(regular_block_size, collector))),
core: Arc::new(RwLock::new(ArenaCore::new(regular_block_size, collector))),
}
}
}
Expand All @@ -63,15 +61,15 @@ impl Arena for MonoIncArena {
type Stats = BasicStats;

fn try_alloc(&self, layout: Layout) -> Option<NonNull<u8>> {
Some(self.core.lock().alloc(layout))
Some(self.core.write().unwrap().alloc(layout))
}

fn stats(&self) -> Self::Stats {
self.core.lock().stats
self.core.read().unwrap().stats
}

fn alloc(&self, layout: Layout) -> NonNull<u8> {
self.core.lock().alloc(layout)
self.core.write().unwrap().alloc(layout)
}
}

Expand Down

0 comments on commit cfaa105

Please sign in to comment.