Page 1 of 1

Thread safety of Raycast

Posted: Wed Feb 25, 2015 12:34 pm
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?

Re: Thread safety of Raycast

Posted: Wed Feb 25, 2015 6:18 pm
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.

Re: Thread safety of Raycast

Posted: Wed Feb 25, 2015 7:55 pm
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).

Re: Thread safety of Raycast

Posted: Wed Feb 25, 2015 7:58 pm
by Norbo
Yup, that's all correct.