Skip to content

Commit

Permalink
Replace std synchronization primitives with parking_lot (bevyengine#210)
Browse files Browse the repository at this point in the history
* Replace std::sync::Mutex with parking_lot::Mutex
* Replace std::sync::RwLock with parking_lot::RwLock
  • Loading branch information
lachlansneff authored Aug 21, 2020
1 parent fc53ff9 commit 1eca55e
Show file tree
Hide file tree
Showing 28 changed files with 174 additions and 246 deletions.
3 changes: 2 additions & 1 deletion crates/bevy_asset/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,5 @@ crossbeam-channel = "0.4.2"
anyhow = "1.0"
thiserror = "1.0"
log = { version = "0.4", features = ["release_max_level_info"] }
notify = { version = "5.0.0-pre.2", optional = true }
notify = { version = "5.0.0-pre.2", optional = true }
parking_lot = "0.10.2"
35 changes: 16 additions & 19 deletions crates/bevy_asset/src/asset_server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,12 @@ use crate::{
use anyhow::Result;
use bevy_ecs::{Res, Resource, Resources};
use crossbeam_channel::TryRecvError;
use parking_lot::RwLock;
use std::{
collections::{HashMap, HashSet},
env, fs, io,
path::{Path, PathBuf},
sync::{Arc, RwLock},
sync::Arc,
thread,
};
use thiserror::Error;
Expand Down Expand Up @@ -107,7 +108,7 @@ impl AssetServer {
where
T: AssetLoadRequestHandler,
{
let mut asset_handlers = self.asset_handlers.write().unwrap();
let mut asset_handlers = self.asset_handlers.write();
let handler_index = asset_handlers.len();
for extension in asset_handler.extensions().iter() {
self.extension_to_handler_index
Expand Down Expand Up @@ -140,14 +141,13 @@ impl AssetServer {
let root_path = self.get_root_path()?;
let asset_folder = root_path.join(path);
let handle_ids = self.load_assets_in_folder_recursive(&asset_folder)?;
self.asset_folders.write().unwrap().push(asset_folder);
self.asset_folders.write().push(asset_folder);
Ok(handle_ids)
}

pub fn get_handle<T, P: AsRef<Path>>(&self, path: P) -> Option<Handle<T>> {
self.asset_info_paths
.read()
.unwrap()
.get(path.as_ref())
.map(|handle_id| Handle::from(*handle_id))
}
Expand All @@ -170,11 +170,11 @@ impl AssetServer {

#[cfg(feature = "filesystem_watcher")]
pub fn watch_for_changes(&self) -> Result<(), AssetServerError> {
let mut filesystem_watcher = self.filesystem_watcher.write().unwrap();
let mut filesystem_watcher = self.filesystem_watcher.write();

let _ = filesystem_watcher.get_or_insert_with(FilesystemWatcher::default);
// watch current files
let asset_info_paths = self.asset_info_paths.read().unwrap();
let asset_info_paths = self.asset_info_paths.read();
for asset_path in asset_info_paths.keys() {
Self::watch_path_for_changes(&mut filesystem_watcher, asset_path)?;
}
Expand All @@ -187,9 +187,7 @@ impl AssetServer {
use notify::event::{Event, EventKind, ModifyKind};
let mut changed = HashSet::new();

while let Some(filesystem_watcher) =
asset_server.filesystem_watcher.read().unwrap().as_ref()
{
while let Some(filesystem_watcher) = asset_server.filesystem_watcher.read().as_ref() {
let result = match filesystem_watcher.receiver.try_recv() {
Ok(result) => result,
Err(TryRecvError::Empty) => {
Expand Down Expand Up @@ -280,8 +278,8 @@ impl AssetServer {
) {
let mut new_version = 0;
let handle_id = {
let mut asset_info = self.asset_info.write().unwrap();
let mut asset_info_paths = self.asset_info_paths.write().unwrap();
let mut asset_info = self.asset_info.write();
let mut asset_info_paths = self.asset_info_paths.write();
if let Some(asset_info) = asset_info_paths
.get(path)
.and_then(|handle_id| asset_info.get_mut(&handle_id))
Expand Down Expand Up @@ -319,7 +317,7 @@ impl AssetServer {
// TODO: watching each asset explicitly is a simpler implementation, its possible it would be more efficient to watch
// folders instead (when possible)
#[cfg(feature = "filesystem_watcher")]
Self::watch_path_for_changes(&mut self.filesystem_watcher.write().unwrap(), path)?;
Self::watch_path_for_changes(&mut self.filesystem_watcher.write(), path)?;
Ok(handle_id)
} else {
Err(AssetServerError::MissingAssetHandler)
Expand All @@ -330,7 +328,7 @@ impl AssetServer {
}

pub fn set_load_state(&self, handle_id: HandleId, load_state: LoadState) {
if let Some(asset_info) = self.asset_info.write().unwrap().get_mut(&handle_id) {
if let Some(asset_info) = self.asset_info.write().get_mut(&handle_id) {
if load_state.get_version() >= asset_info.load_state.get_version() {
asset_info.load_state = load_state;
}
Expand All @@ -340,7 +338,6 @@ impl AssetServer {
pub fn get_load_state_untyped(&self, handle_id: HandleId) -> Option<LoadState> {
self.asset_info
.read()
.unwrap()
.get(&handle_id)
.map(|asset_info| asset_info.load_state.clone())
}
Expand All @@ -367,7 +364,7 @@ impl AssetServer {

fn send_request_to_loader_thread(&self, load_request: LoadRequest) {
// NOTE: This lock makes the call to Arc::strong_count safe. Removing (or reordering) it could result in undefined behavior
let mut loader_threads = self.loader_threads.write().unwrap();
let mut loader_threads = self.loader_threads.write();
if loader_threads.len() < self.max_loader_threads {
let loader_thread = LoaderThread {
requests: Arc::new(RwLock::new(vec![load_request])),
Expand All @@ -378,9 +375,9 @@ impl AssetServer {
} else {
let most_free_thread = loader_threads
.iter()
.min_by_key(|l| l.requests.read().unwrap().len())
.min_by_key(|l| l.requests.read().len())
.unwrap();
let mut requests = most_free_thread.requests.write().unwrap();
let mut requests = most_free_thread.requests.write();
requests.push(load_request);
// if most free thread only has one reference, the thread as spun down. if so, we need to spin it back up!
if Arc::strong_count(&most_free_thread.requests) == 1 {
Expand All @@ -399,7 +396,7 @@ impl AssetServer {
thread::spawn(move || {
loop {
let request = {
let mut current_requests = requests.write().unwrap();
let mut current_requests = requests.write();
if current_requests.len() == 0 {
// if there are no requests, spin down the thread
break;
Expand All @@ -408,7 +405,7 @@ impl AssetServer {
current_requests.pop().unwrap()
};

let handlers = request_handlers.read().unwrap();
let handlers = request_handlers.read();
let request_handler = &handlers[request.handler_index];
request_handler.handle_request(&request);
}
Expand Down
1 change: 1 addition & 0 deletions crates/bevy_audio/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ bevy_ecs = {path = "../bevy_ecs", version = "0.1"}
# other
anyhow = "1.0"
rodio = {version = "0.11", default-features = false}
parking_lot = "0.10.2"

[features]
mp3 = ["rodio/mp3"]
Expand Down
7 changes: 4 additions & 3 deletions crates/bevy_audio/src/audio_output.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
use crate::AudioSource;
use bevy_asset::{Assets, Handle};
use bevy_ecs::Res;
use parking_lot::RwLock;
use rodio::{Decoder, Device, Sink};
use std::{collections::VecDeque, io::Cursor, sync::RwLock};
use std::{collections::VecDeque, io::Cursor};

/// Used to play audio on the current "audio device"
pub struct AudioOutput {
Expand All @@ -27,11 +28,11 @@ impl AudioOutput {
}

pub fn play(&self, audio_source: Handle<AudioSource>) {
self.queue.write().unwrap().push_front(audio_source);
self.queue.write().push_front(audio_source);
}

pub fn try_play_queued(&self, audio_sources: &Assets<AudioSource>) {
let mut queue = self.queue.write().unwrap();
let mut queue = self.queue.write();
let len = queue.len();
let mut i = 0;
while i < len {
Expand Down
1 change: 1 addition & 0 deletions crates/bevy_diagnostic/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,4 @@ bevy_ecs = { path = "../bevy_ecs", version = "0.1" }

# other
uuid = { version = "0.8", features = ["v4", "serde"] }
parking_lot = "0.10"
14 changes: 5 additions & 9 deletions crates/bevy_diagnostic/src/system_profiler.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,7 @@
use crate::{Diagnostic, DiagnosticId, Diagnostics};
use bevy_ecs::{Profiler, Res, ResMut};
use std::{
borrow::Cow,
collections::HashMap,
sync::{Arc, RwLock},
time::Instant,
};
use parking_lot::RwLock;
use std::{borrow::Cow, collections::HashMap, sync::Arc, time::Instant};

#[derive(Debug)]
struct SystemRunInfo {
Expand All @@ -28,7 +24,7 @@ pub struct SystemProfiler {

impl Profiler for SystemProfiler {
fn start(&self, scope: Cow<'static, str>) {
let mut system_profiles = self.system_profiles.write().unwrap();
let mut system_profiles = self.system_profiles.write();
let profiles = system_profiles
.entry(scope.clone())
.or_insert_with(SystemProfiles::default);
Expand All @@ -38,7 +34,7 @@ impl Profiler for SystemProfiler {

fn stop(&self, scope: Cow<'static, str>) {
let now = Instant::now();
let mut system_profiles = self.system_profiles.write().unwrap();
let mut system_profiles = self.system_profiles.write();
let profiles = system_profiles.get_mut(&scope).unwrap();
if let Some(current_start) = profiles.current_start.take() {
profiles.history.push(SystemRunInfo {
Expand All @@ -54,7 +50,7 @@ pub fn profiler_diagnostic_system(
system_profiler: Res<Box<dyn Profiler>>,
) {
let system_profiler = system_profiler.downcast_ref::<SystemProfiler>().unwrap();
let mut system_profiles = system_profiler.system_profiles.write().unwrap();
let mut system_profiles = system_profiler.system_profiles.write();
for (scope, profiles) in system_profiles.iter_mut() {
if diagnostics.get(profiles.diagnostic_id).is_none() {
diagnostics.add(Diagnostic::new(profiles.diagnostic_id, &scope, 20))
Expand Down
1 change: 1 addition & 0 deletions crates/bevy_ecs/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,4 @@ rayon = "1.3"
crossbeam-channel = "0.4.2"
fixedbitset = "0.3.0"
downcast-rs = "1.1.1"
parking_lot = "0.10"
Loading

0 comments on commit 1eca55e

Please sign in to comment.