I am new to C++ concurrency.I started working with boost threads as those supply cross platform solution.Most of the examples I have seen so far deal with passing separate function into threads.Like this for instance.In my case I have a class which has instances of couple of more classes, in my case OpenGL context and rendering related stuff. I have learnt that assigning an object to the thread is done this way:
mythread=new boost::thread(boost::ref(*this));
Where *this is the pointer to the instance inside which it is called. But what about other classes which are composite in this class instance?Should I do the same for each of them or they are threaded automatically once I call it on the host class? My original problem is outlined in this thread.So , once I fire the thread it looks like OpenGL context remains in the main thread.(See the GPUThread class at the bottom).
Here is my threaded class:
GPUThread::GPUThread(void)
{
_thread =NULL;
_mustStop=false;
_frame=0;
_rc =glMultiContext::getInstance().createRenderingContext(GPU1);
assert(_rc);
glfwTerminate(); //terminate the initial window and context
if(!glMultiContext::getInstance().makeCurrent(_rc)){
printf("failed to make current!!!");
}
// init engine here (GLEW was already initiated)
engine = new Engine(800,600,1);
}
void GPUThread::Start(){
printf("threaded view setup ok");
///init thread here :
_thread=new boost::thread(boost::ref(*this));
_thread->join();
}
void GPUThread::Stop(){
// Signal the thread to stop (thread-safe)
_mustStopMutex.lock();
_mustStop=true;
_mustStopMutex.unlock();
// Wait for the thread to finish.
if (_thread!=NULL) _thread->join();
}
// Thread function
void GPUThread::operator () ()
{
bool mustStop;
do
{
// Display the next animation frame
DisplayNextFrame();
_mustStopMutex.lock();
mustStop=_mustStop;
_mustStopMutex.unlock();
} while (mustStop==false);
}
void GPUThread::DisplayNextFrame()
{
engine->Render(); //renders frame
if(_frame == 101){
_mustStop=true;
}
}
GPUThread::~GPUThread(void)
{
delete _view;
if(_rc != 0)
{
glMultiContext::getInstance().deleteRenderingContext(_rc);
_rc = 0;
}
if(_thread!=NULL)delete _thread;
}
When this class runs OpenGL context emits errors.I can't read pixel data from the buffers.I suppose it is because I init _rc (render context) and set current context before calling this:
_thread=new boost::thread(boost::ref(*this));
I tried doing it after the thread init but then it skips right into thread function leaving the objects not initialized. So what is the right way to set boost thread on a class with all its content?