Karsten Döring
April 9th, 1999, 04:56 AM
Hi,
I have some procedures which all are searching and modifying an array. My program can be called at the same time by more than one person, so i have to prevent that all users are working in that array at the same time.
is it possible to solve this with following code in each procedure which uses this array?
{
CCriticalSection cs;
cs.Lock()
// my code
cs.Unlock()
}
I hope u can help me.
Thanx in advance.
Candan
April 9th, 1999, 05:10 AM
try CSemaphore
hope help
April 9th, 1999, 07:45 AM
Hi
You need to use a CCriticalSection to protect your array from simultaneous accesses by multiple threads within a single process, but it's a bit more complicated than in your code. Microsoft's terminology is very confusing here: most people use "critical section" to refer to a section of code which modifies a shared data structure, so only one thread at a time may be executing a critical section of code.
Microsoft's CCriticalSection is actually a lock which prevents multiple threads from entering a critical section at the same time. The critical section is the region of code between the Lock() and Unlock() calls.
So - you mustn't have a separate CCriticalSection in each function, because each thread would get its own copy. Instead you just declare a single CCriticalSection, and the best place to put it is next to the array that it is protecting.
You could call CCriticalSection::Lock() and CCriticalSection::Unlock() directly from your functions, but it's better to use a CSingleLock object, as follows:
int array[100]; // Shared array
CCriticalSection crit; // Protects array
void func ( ) // Function which modifies array
{
CSingleLock lock ( &crit, TRUE ); // Lock the critical section
...
// Code that modifies array in here
return; // Automatically unlocks critical section
}
This way you can be sure that the lock is always freed, no matter how func() returns (e.g. by a return in the middle, a return at the end, or because an exception is thrown).
I've assumed you are protecting against simultaneous access by multiple threads. If your array is in shared memory and you want to protect against simultaneous access by multiple processes, then just replace the CCriticalSection by a CMutex.
HTH