Thread safety of Raycast

Discuss any questions about BEPUphysics or problems encountered.
Post Reply
Crea
Posts: 10
Joined: Tue Feb 24, 2015 10:54 am

Thread safety of Raycast

Post by Crea »

Hi again, sorry for another question so soon after my last :)

It appears that Raycasting into a Space which is updated asynchronously is not thread safe, is this correct? Is the intention to ray cast against the buffered list of entities via SpaceObject buffer? Or would I be better off en queuing raycast requests onto the same background thread as the Space is updating on?
Norbo
Site Admin
Posts: 4929
Joined: Tue Jul 04, 2006 4:45 am

Re: Thread safety of Raycast

Post by Norbo »

A ray cast against an asynchronously updated Space is indeed unsafe; the broad phase acceleration structure could be updated while the query is running, corrupting the result.

Enqueuing the query for handling on the Space's thread is one of the better approaches in terms of performance, since it avoids any long synchronization. If performance is more important than logical complexity concerns, I would recommend doing it this way.

Another simpler and slower approach is to acquire a lock on the Space.BroadPhase.Locker object before doing ray casts. This could end up blocking the query thread for milliseconds while the broad phase runs.
Crea
Posts: 10
Joined: Tue Feb 24, 2015 10:54 am

Re: Thread safety of Raycast

Post by Crea »

Sorry, my question was driven by some initial poor understanding of the intended asynchronous use of the engine.

I think I get it now; the engine is not thread safe, but can be updated asynchronously (given that it's self contained), and there's some useful buffers to allow you to queue adds and removals to a Space in a thread safe fashion, and query entity transform state in a similar way. Other than that, though, you have to either marshal whatever info you need back and forth across the thread boundary, or synchronise (and there's some helpful structures to lock on).
Norbo
Site Admin
Posts: 4929
Joined: Tue Jul 04, 2006 4:45 am

Re: Thread safety of Raycast

Post by Norbo »

Yup, that's all correct.
Post Reply