Skip to content

Commit

Permalink
Merge pull request #248 from stjepang/num-shards-in-constructor
Browse files Browse the repository at this point in the history
Add num_shards argument to ShardedLock::new
  • Loading branch information
Stjepan Glavina authored Dec 26, 2018
2 parents e10df68 + b63ccde commit 91e2ecf
Show file tree
Hide file tree
Showing 3 changed files with 7 additions and 7 deletions.
1 change: 0 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ std = ["crossbeam-epoch/std", "crossbeam-utils/std"]
[dependencies]
cfg-if = "0.1"
lazy_static = "1.1.0"
num_cpus = "1.8.0"
parking_lot = "0.7"

[dependencies.crossbeam-channel]
Expand Down
1 change: 0 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,6 @@ cfg_if! {

#[macro_use]
extern crate lazy_static;
extern crate num_cpus;
extern crate parking_lot;

mod ms_queue;
Expand Down
12 changes: 7 additions & 5 deletions src/sharded_lock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ use std::ops::{Deref, DerefMut};
use std::thread::{self, ThreadId};

use crossbeam_utils::CachePadded;
use num_cpus;
use parking_lot::{Mutex, RwLock, RwLockReadGuard, RwLockWriteGuard};

/// A scalable reader-writer lock.
Expand Down Expand Up @@ -42,12 +41,15 @@ unsafe impl<T: Send> Send for ShardedLock<T> {}
unsafe impl<T: Send + Sync> Sync for ShardedLock<T> {}

impl<T> ShardedLock<T> {
/// Creates a new `ShardedLock` initialized with `value`.
pub fn new(value: T) -> ShardedLock<T> {
/// Creates a new `ShardedLock`.
///
/// The lock is initialized to `value`. The actual number of shards used might be slightly
/// different from `num_shards` because that argument is only considered to be a *hint*. A
/// generally good number of shards to use is the number of available CPUs.
pub fn new(value: T, num_shards: usize) -> ShardedLock<T> {
// The number of shards is a power of two so that the modulo operation in `read` becomes a
// simple bitwise "and".
let num_shards = num_cpus::get().next_power_of_two();

let num_shards = num_shards.max(1).next_power_of_two();
ShardedLock {
shards: (0..num_shards)
.map(|_| CachePadded::new(RwLock::new(())))
Expand Down

0 comments on commit 91e2ecf

Please sign in to comment.