Creating CSingleLock object
Hello!
I have a program which has one array which must be shared between multiple resources. The structure
of the code looks like this:
// container for various information
class OtherClass
{
public:
CString name, ..., ..., ..;
};
// holds member functions to add / remove / retrieve info from OtherClass
class MyClass : public OtherClass
{
public:
add_class (CString*, ..., ..., ..);
remove_class(CString*);
private:
OtherClass *array[1000];
};
The problem is that sometimes, the array in MyClass must be protected from modification.
Example: While using add_class( ), remove_class( ) must wait until add_class has finished it's
modifications.
I have heard about CSingleLock(CSyncObject*, BOOL); and I think it might be the solution.
But how do I create a CSingleLock object out of OtherClass *array[1000]; ?
/ Johan M
Re: Creating CSingleLock object
The sync-objects (CSingleLock, CMutex, CSemaphore, CCriticalSection...) are all kernel sync objects which are used in multithreading applications to syncronize the threads and protect data. If you have not a multthreaded application, which means you have only one thread running, it is not possible that both functions (add_class, remove_class) are called at the same time. So no sync objects are needed. If you have a multithread application, it is possible that one thread calls add_class while another thread calls remove_class. To prevent your data, you have to syncronize the threads. To do this in your case a CCriticalSection is enough. Do it like this:
Add protected member CCriticalSection (m_cs) in MyClass.
In Add_class first call m_cs.Lock(). After finish call m_cs.Unlock().
The same in remove_class: first m_cs.Lock(), after finish m_cs.Unlock().
Hope this helps