Make `Rc<RefCell<blah>>` thread-safe


#1

Hello,

I am using ggez, specs, and nphysics2d to make a game and I want to store nphysics2d's RigidBodyHandles in spec Components. To do this, I require RigidBodyHandle to be thread-safe.

RigidBodyHandle is defined as:

/// A shared, mutable, rigid body.
pub type RigidBodyHandle = Rc<RefCell<RigidBody>>;

How can I make RigidBodyHandle thread-safe? Is it even possible?


#2

The thread-safe equivalent is Arc<Mutex<T>>.


#3

Another alternative would be Arc<RwLock<T>>.

I like to think of RefCell as “single-threaded RwLock that panics instead of blocking”. :slight_smile:


#4

That doesn’t solve the problem since I am getting that type from a third-party library :confused:


#5

I don’t think there’s any way to wrap Rc<RefCell<T>> to be thread-safe, but maybe you can send a temporary reference instead? i.e. call borrow_mut() to get &mut T and wrap that in a mutex for sharing between threads. That would require threading with non 'static lifetimes though, and I have no idea if that can fit into specs.


#6

Unfortunately, nphysics is incompatible with ECS. It’s really sad we cannot use it together with Specs.

Is there any other 2D physics library you could use?


#7

nphysics was my first choice since I wanted to avoid dealing with linking other libraries or building wrappers.
I wanted to use wrapped2d but it had a build dependency on gcc which is a no-go for me.

I will hack around the limitation for now :man_shrugging: