Original Post
Hey all, I'm trying to stop my game code from chugging at the moment by making as much of the time consuming code asynchronous and thread safe, as possible. I have managed to get the vast majority of this accomplished, but I'm struggling a little with some code which I am unable to make thread safe because it is using a DirectX device and is very low level code within the engine (non multithreading aware D3D Device for performance reasons). The code in question was not written by me and is very low level which makes it even harder to refactor. I'm wondering if it would be safe to move the non threadsafe code into its own thread and halt execution of the main thread whilst the job in question is processing. The idea would be to then code an object which, when instantiated, will periodically stop the current thread from processing and allow the main thread to continue. When the main thread has sufficient processing time remaining in a cycle, the main thread will again be locked and the thread the job belongs to will be allowed to continue. Repeat this ad infinatum until the job has completed. All that would then be required is that the code instantiate these objects to give the main thread a breather every now and again and the job is effectively spread over several cycles whilst hopefully still remaining thread safe. Even though the code is itself not threadsafe, the main thread is always locked whilst the code is executing and nothing would use the code in any other thread. I always get my head caught up in thread safety stuff, so firstly I'm wondering if my scheme sounds like it would be threadsafe despite the fact the code is not running in the main thread and is not inherently thread safe. Secondly, I wonder if anyone might have a better suggestion as to how to cope with spreading code that takes a while to execute over several frames without having to drastically refactor it? The code in question is making lots of calls which are not very expensive on their own, but add up over a period of time. Roughly 6,000 calls to about 5 different functions is taking about 0.05 seconds which is the cause of my chug as far as I can tell. Any advice would be very much appreciated :) I can provide extra info if needed. Many thanks, Steve O