CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Apr 1999
    Location
    Germany
    Posts
    53

    CCriticalSection

    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.


  2. #2
    Join Date
    May 1999
    Posts
    40

    Re: CCriticalSection

    try CSemaphore

    hope help



  3. #3
    Guest

    Re: CCriticalSection

    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


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured