If your only needing read access to the protected structers/classes, then let your reading thread get a mutex lock, pass it a copy of the information requested, then release the lock.
Your reading thread will at times have outdated information. How outdated is entirly up to you.
Say your useing this information to draw to the screen, you get a mutex lock to the information, then copy it and release the lock.
You now have a snapshot of a time index, as you start your drawing code, the other thread is free to continue processing the next time index.
anyway hop this helps, i found it a while back when i had a problem like this one.
Code:
#pragma once
#ifndef _MUTEX_LOCK_H
#define _MUTEX_LOCK_H
#include <windows.h>
class Mutex{ friend class Lock;
public:
Mutex ()
{
InitializeCriticalSection (& _critSection);
}
~Mutex ()
{
DeleteCriticalSection (& _critSection);
}
private:
void Acquire ()
{
EnterCriticalSection (& _critSection);
}
void Release ()
{
LeaveCriticalSection (& _critSection);
}
CRITICAL_SECTION _critSection;
};
class Lock{
public:
// Acquire the state of the semaphore
Lock ( Mutex & mutex )
: _mutex(mutex)
{
_mutex.Acquire();
}
// Release the state of the semaphore
~Lock ()
{
_mutex.Release();
}
private:
Mutex & _mutex;
};
class varablelock{
public:
//method to get Instance of class
static varablelock *getInstance( void )
{
//Note that the class is only created when this method is called first time
if(!instance_)
instance_ = new varablelock;
return instance_;
}
//method to delete Instance of class
static void deleteInstance( void )
{
if(instance_)
delete instance_;
instance_ = NULL;
//important as this can create dead reference problems
}
Mutex mutex_;
varablelock() {};
~varablelock() {};
private:
//variable to store the instance of singleton
static varablelock *instance_;
//default constructor should be private to prevent instantiation
//destructor should be made private so no one can delete this accidently
//We also need to prevent copy being created of the object
varablelock(const varablelock&);
};
#endif
and to use it do something like this
Code:
varablelock output_lock;
.....
if( update_state ){
Lock thread_safe( output_lock );
//Mutex is locked on so we have sole access to data
current_state = physic_engine.Copy(&time_index);
}
//mutex is destroyed after if statement