-
Notifications
You must be signed in to change notification settings - Fork 252
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
use a vector instead of thread local
- Loading branch information
1 parent
89314af
commit db1c48f
Showing
3 changed files
with
21 additions
and
10 deletions.
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,27 +1,40 @@ | ||
use std::sync::{LockResult, RwLock, RwLockReadGuard, RwLockWriteGuard}; | ||
use thread_local::ThreadLocal; | ||
|
||
/// A RwLock that leverages thread locals to avoid contention. | ||
pub struct LrwLock<A: Send> { | ||
inner: ThreadLocal<RwLock<A>>, | ||
value: A, | ||
inner: Vec<RwLock<A>>, | ||
} | ||
|
||
const SIZE: usize = 16; | ||
|
||
impl<A: Clone + Send> LrwLock<A> { | ||
/// Create a new LrwLock. | ||
pub fn new(value: A) -> Self { | ||
Self { inner: ThreadLocal::new(), value } | ||
let mut inner = Vec::with_capacity(SIZE); | ||
for _ in 1..SIZE { | ||
inner.push(RwLock::new(value.clone())); | ||
} | ||
|
||
Self { inner } | ||
} | ||
|
||
/// Lock the LrwLock for reading. | ||
pub fn read(&self) -> LockResult<RwLockReadGuard<'_, A>> { | ||
self.inner.get_or(|| RwLock::new(self.value.clone())).read() | ||
let id = thread_id(); | ||
|
||
self.inner[id % SIZE].read() | ||
} | ||
|
||
/// Lock the LrwLock for writing. | ||
pub fn write(&self) -> LockResult<RwLockWriteGuard<'_, A>> { | ||
self.inner | ||
.get_or(|| RwLock::new(self.value.clone())) | ||
.write() | ||
let id = thread_id(); | ||
|
||
self.inner[id % SIZE].write() | ||
} | ||
} | ||
|
||
fn thread_id() -> usize { | ||
format!("{:?}", std::thread::current().id()) | ||
.parse::<usize>() | ||
.unwrap() | ||
} |
db1c48f
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Running 30s test @ http://localhost:8000/graphql
4 threads and 100 connections
358176 requests in 30.03s, 1.80GB read
Requests/sec: 11929.19
Transfer/sec: 61.23MB