Page 1 of 1
Exceptions When Multithreading
Posted: Sat Dec 08, 2012 7:19 pm
by jsuffolk
Hi, my game has been running into CPU-related lag and I'd like to multithread the physics as this seems to help. However, upon killing an enemy I call
to remove their physics body from the simulation. When running on a single thread this code works without problems, but when multithreaded it throws exceptions - specifically ArgumentOfRangeExceptions and NullReferenceExceptions. I'm multithreading the physics with the code snippet below:
Code: Select all
if (Environment.ProcessorCount > 1)
{
for (int i = 0; i < Environment.ProcessorCount - 1; i++)
{
Space.ThreadManager.AddThread();
}
}
Re: Exceptions When Multithreading
Posted: Sat Dec 08, 2012 8:10 pm
by Norbo
Is the Space.Remove being called from an immediate event handler or other asynchronous context? Space.Remove and most other methods unless specifically marked otherwise are not thread safe.
(Removing entities from the Space from an immediate event handler, even if not asynchronous, will also likely cause a problem of one kind or another too; the engine expects its internal structures are stable for the duration of a space update.)
Re: Exceptions When Multithreading
Posted: Wed Dec 19, 2012 3:11 pm
by chebob69
I've just realised I'll probably have issues with this in the near future as well. I'm just running the single thread at the moment so this hasn't been an issue. How would you go about adding and removing objects in a multi-threaded simulation?
Re: Exceptions When Multithreading
Posted: Wed Dec 19, 2012 8:20 pm
by Norbo
You can add/remove entities from the space with perfect safety so long you do it between space updates, rather than during a space update. This is true whether or not internal multithreading is in use.
Using internal multithreading just makes the physics simulation threaded. Outside of the space update, no physics threads are doing any work, so there's no issues. Asynchronous interaction with the engine is a separate and more dangerous concept; if you can't guarantee that the space update isn't running at the time of interaction, all interactions must be performed with extreme care (usually in the form of buffers of one kind or another).
Re: Exceptions When Multithreading
Posted: Sun Dec 23, 2012 9:51 pm
by chebob69
Gotcha, glad that won't be a problem. I'm not even sure why I'd have done it during a space update, wouldn't that imply you'd edited the space class?
Re: Exceptions When Multithreading
Posted: Sun Dec 23, 2012 10:44 pm
by Norbo
I'm not even sure why I'd have done it during a space update, wouldn't that imply you'd edited the space class?
Not necessarily; for example, removing an entity from an immediate collision event would occur during the execution of the update. That would be a no-no.
The other common case is a separate thread interfering with the execution of the physics thread(s). That separate thread can wreak all sorts of havoc if used without care.