How can I save state from script in a multithreaded engine?
- by Peter Ren
We are building a multithreaded game engine and we've encountered some problems as described below.
The engine have 3 threads in total: script, render, and audio. Each frame, we update these 3 threads simultaneously. As these threads updating themselves, they produce some tasks and put them into a public storage area. As all the threads finish their update, each thread go and copy the tasks for themselves one by one. After all the threads finish their task copying, we make the threads process those tasks and update these threads simultaneously as described before. So this is the general idea of the task schedule part of our engine.
Ok, well, all the task schedule part work well, but here's the problem:
For the simplest, I'll take Camera as an example:
local oldPos = camera:getPosition() -- ( 0, 0, 0 )
camera:setPosition( 1, 1, 1 ) -- Won't work now, cuz the render thread will process the task at the beginning of the next frame
local newPos = camera:getPosition() -- Still ( 0, 0, 0 )
So that's the problem: If you intend to change a property of an object in another thread, you have to wait until that thread process this property-changing message. As a result, what you get from the object is still the information in the last frame.
So, is there a way to solve this problem? Or are we build the task schedule part in a wrong way? Thanks for your answers :)