Hi,
my program runs with multiple threads. The problem is when creating a new object the object often needs data from methods or objects which are not multithreading safe and therefore not available.
Let's take for instance OpenGL which is not synchronized and spits out an error when you try to access it from another thread.
This new object I want to create might needs to load a texture, or vertices or whatever onto the gpu to work properly. Maybe it also needs a physical reference in the physics engine which is also only single-threaded like OpenGL.
How exactly do I create an object at an unknown later time?
Example code of such an object I try to use together with the engine:
class Test {
String texturePath;
float x, y;
Body body;
int texture;
// thread 1 creates object
Test( String texturePath, float x, float y ) {
this.texturePath = texturePath;
this.x = x;
this.y = y;
}
// thread 2 completes initialization with missing data
void init( OGLContext ogl ) {
texture = ogl.createTexture( texturePath );
}
// thread 3 completes initialization with missing data
void init( Physic physXContext ) {
body = physXContext.createBody( x, y );
}
}
This is how I am doing it right now.
The problem occurs when you now think about the variables that are now left in the object used to save the data to actually initialize the needed non-threadsafe data by the other cores.
Now we have 2 floats and a string left, taking up memory and endangering program safety and stability because they could be accidentially used though they are null-pointers or contain old-data.
I thought about maybe creating Factory"objects" (I googled that term and it doesn't exists) for every object I want to create which saves the data like above but instead creates the actual object containing all the data after all init()-Methods were called.
However, I am not sure if creating and destroying a new Factoryobject everytime I want to create a new object is really a better idea then how it is right now.
My solutions seem to be ugly and error-prone with lots of redundant work. Any ideas how I could improve that?
It would be so great if I could just remove the variables completly after they are not needed anymore ^^
Thank you very much
With Best Regards