From ce3068a2a4b39f5afbfb02aecb22cb563edf1627 Mon Sep 17 00:00:00 2001 From: JoJoJet <21144246+JoJoJet@users.noreply.github.com> Date: Fri, 17 Feb 2023 00:22:57 +0000 Subject: [PATCH] Allow shared access to `SyncCell` for types that are already `Sync` (#7718) # Objective The type `SyncCell` (added in #5483) is used to force any wrapped type to be `Sync`, by only allowing exclusive access to the wrapped value. This restriction is unnecessary for types which are already `Sync`. --- ## Changelog + Added the method `read` to `SyncCell`, which allows shared access to values that already implement the `Sync` trait. --- crates/bevy_utils/src/synccell.rs | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/crates/bevy_utils/src/synccell.rs b/crates/bevy_utils/src/synccell.rs index 4902cd03c3eb8..55102dede4a58 100644 --- a/crates/bevy_utils/src/synccell.rs +++ b/crates/bevy_utils/src/synccell.rs @@ -29,6 +29,14 @@ impl SyncCell { &mut self.inner } + /// For types that implement [`Sync`], get shared access to this `SyncCell`'s inner value. + pub fn read(&self) -> &T + where + T: Sync, + { + &self.inner + } + /// Build a mutable reference to a `SyncCell` from a mutable reference /// to its inner value, to skip constructing with [`new()`](SyncCell::new()). pub fn from_mut(r: &'_ mut T) -> &'_ mut SyncCell { @@ -38,6 +46,6 @@ impl SyncCell { } // SAFETY: `Sync` only allows multithreaded access via immutable reference. -// As `SyncCell` requires an exclusive reference to access the wrapped value, -// marking this type as `Sync` does not actually allow threaded access to the inner value. +// As `SyncCell` requires an exclusive reference to access the wrapped value for `!Sync` types, +// marking this type as `Sync` does not actually allow unsychronized access to the inner value. unsafe impl Sync for SyncCell {}