CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 11 of 11
  1. #1
    Join Date
    Jan 2012
    Location
    India
    Posts
    193

    Confused about the usage of Critical Section ..

    I am using a thread in my application .. A DLL is written for In and Out instructions for hardware ICS and to read FIFO.

    My code is

    CCriticalSection crdll , crsec ;

    UINT ThreadReceiveData(LPVOID param)
    {

    for ( ; ; ) {

    if (bTerminate) break; // bTerminate = 1 in Doc template destructor

    crdll.Lock();

    do {

    read data ;

    if ( data is not valid) break;

    crdll.Lock();

    if (data of type 1) process data;

    crdll.Unlock();


    crsec.Lock();

    if (data of type 2) process data;

    crsec.Unlock();


    } while valid data

    crdll.UnLock();

    }

    return 1;

    }


    I am confused , how and when I should use Ctitical Section ? The program works fine but I am
    not happy as this is main routine of the program and I have not understood it properly.


    PL GUIDE ..
    Last edited by new_2012; December 12th, 2012 at 05:35 AM.

  2. #2
    Join Date
    Apr 2000
    Location
    Belgium (Europe)
    Posts
    4,626

    Re: Confused about the usage of Critical Section ..

    1) use [code ] markup when posting code
    2) you're not using it right, you're multiple locking the same critical section. While that is technically allowed, in this particular case, it shows signs you're not really understanding what a critical section is.


    The simple 'visual' explanation is something like follows.

    A critical section is intended to protect a (short) bit of code in such a way that only 1 thread at a time can ever execute the bit of code between the Lock() and Unlock() of the critical section.


    the assumption is that the bit of code you're trying to protect is (significanly) shorter than a timeslice on your computer. Meaning you'll typically only use it to protect 'trivial' code. If you have code that could run for 'a long time' and you need to prevent multiple threads from executing then a mutex would be better suited.

    The key difference here is that trying to enter a locked critical section will cause your current thread to "spin" waiting for the CS to become available and will go to sleep afterwards if it's not available, while a mutex would put the thread to sleep 'immediately'.

    If the protected code is short, the spin will be aborted and your timeslice continues, you just saved an expensive task switch. If the protected code is long, the spin will run out, and you will have waited in vain and STILL end up with a task switch anyway, so the mutex would have been faster.

    The technical approach to it is that you can wait on a mutex to become signalled, but cannot wait on a critical section.

  3. #3
    Join Date
    Jan 2012
    Location
    India
    Posts
    193

    Re: Confused about the usage of Critical Section ..

    Thank u sir ..

    I was in same doubt that I am using multiple critical section .. now I will rewrite the code again ..

    will read more on Mutex ..

    really thank u ..

    one more question ..

    I am using CCriticalSection crdll in my thread .. then for other functions , should I use different variable object of CriticalSection ?

  4. #4
    Join Date
    Jul 2005
    Location
    Netherlands
    Posts
    2,042

    Re: Confused about the usage of Critical Section ..

    Quote Originally Posted by new_2012 View Post
    I am using CCriticalSection crdll in my thread .. then for other functions , should I use different variable object of CriticalSection ?
    You should use a CS to avoid data races. This can happen from a single function (called from different threads) or multiple functions that access the same memory location. See Hans Boehm's introduction here.
    Cheers, D Drmmr

    Please put [code][/code] tags around your code to preserve indentation and make it more readable.

    As long as man ascribes to himself what is merely a posibility, he will not work for the attainment of it. - P. D. Ouspensky

  5. #5
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: Confused about the usage of Critical Section ..

    Does more that one process access this dll?

  6. #6
    Join Date
    Jan 2012
    Location
    India
    Posts
    193

    Smile Re: Confused about the usage of Critical Section ..

    Thanks to all of you ..

    Yes , the function was being used by different processes.

    The problem was , the code was functioning fine on WIN XP ,

    but when I ported software on WIN 7 , there were many problems due to improper usage
    of CS . After some time , prog was getting terminated with error message.

    Now , yesterdat it self , I put proper Locks and Unlocks to protect Data and things seem to be ok.

    I dont know how to put Tags in the code ..

  7. #7
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: Confused about the usage of Critical Section ..

    Quote Originally Posted by new_2012 View Post
    Thanks to all of you ..

    Yes , the function was being used by different processes.

    The problem was , the code was functioning fine on WIN XP ,

    but when I ported software on WIN 7 , there were many problems due to improper usage
    of CS . After some time , prog was getting terminated with error message.

    Now , yesterdat it self , I put proper Locks and Unlocks to protect Data and things seem to be ok.

    I dont know how to put Tags in the code ..
    Critical Sections don't work across processes. You'll need to use a kernel mode synchronization object like a mutex for cross process synchronization.

    Also, look into using RAII to release the locks so you don't have to make explicit unlock calls (and thereby avoid the issues created by not releasing a lock).

  8. #8
    Join Date
    Apr 1999
    Posts
    27,449

    Re: Confused about the usage of Critical Section ..

    Quote Originally Posted by new_2012 View Post
    The problem was , the code was functioning fine on WIN XP ,
    Which means it doesn't function "fine". You are just lucky that right now, things seem to run fine on XP.

    Distribute that application to hundreds or thousands of customers who run XP in different ways, different setups, different background processes running, different hardware, etc. and you would more than likely see that something is wrong (one or more customer will report a crash or inconsistent behaviour with your application).
    Now , yesterdat it self , I put proper Locks and Unlocks to protect Data and things seem to be ok.
    Your code may still have problems, as Arjay pointed out.

    First, mutexes are used across processes, not critical sections.

    Second, even if you use a mutex, this is an issue:
    Code:
    crdll.Lock();
    if (data of type 1) process data;
    crdll.Unlock();
    What if "process data" throws an exception? You now have a lock that was never unlocked since it never got to the "crdll.Unlock" line of code. Please see the CSingleLock class, since you're using MFC. The CSingleLock class is an example of an RAII object.

    The destructor of CSingleLock is called whenever it goes out of scope for any reason whatsoever. This means that multiple return points, exceptions being thrown, etc. are all going to unlock the handle.

    http://msdn.microsoft.com/en-US/libr...=vs.80%29.aspx
    After use of the resource is complete, either call the Unlock function if the CSingleLock object is to be used again, or allow the CSingleLock object to be destroyed.
    Regards,

    Paul McKenzie

  9. #9
    Join Date
    Jan 2012
    Location
    India
    Posts
    193

    Smile Re: Confused about the usage of Critical Section ..

    Thank u Paul and Arjay and all of you .

    I will think on the program with directions given by you.

    I will learn everything in detail and will think on Exception Throw .. which I never thought of.

    Really thanks a lot ..

  10. #10
    Join Date
    Apr 2000
    Location
    Belgium (Europe)
    Posts
    4,626

    Re: Confused about the usage of Critical Section ..

    Quote Originally Posted by Paul McKenzie View Post
    First, mutexes are used across processes, not critical sections.
    This isn't entirely correct.

    The big difference between the two is that a mutex is a waitable sync object (can be used in a WaitForSingleObject(Ex) or WaitForMultipleObjects(Ex) or one of the other wait functions), whereas a critical section is not.
    You cannot wait on a critical section to become available, you can sort of do this yourself in a polling loop with TryEnterCriticalSection(), but that pretty much means you really should have used a mutex +wait instead.

    A critical section is also lighter weight than a mutex. (faster)

    A named Mutex CAN be used accross processes, an unnamed mutex cannot. Yes, there's a difference, a unnamed mutex is faster than a named one. But there are cases where you would very much use a mutex over a critical section even if inter process is not even an issue.


    Ignoring the waitable feature, behaviourly a critical section and a mutex are similar and you could interchange them for most purposes. But from a design/semantic p.o.v. I personally won't ever use a critical section for anything other than guarding a "small" section of code where the lock/unlock happen in the same function (or in a contructor and matchign destructor). If I have a need for a lock in one place and the matching unlock in a totally different function, then I'd use a mutex.

  11. #11
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: Confused about the usage of Critical Section ..

    Quote Originally Posted by OReubens View Post
    This isn't entirely correct.

    The big difference between the two is that a mutex is a waitable sync object (can be used in a WaitForSingleObject(Ex) or WaitForMultipleObjects(Ex) or one of the other wait functions), whereas a critical section is not.
    You cannot wait on a critical section to become available, you can sort of do this yourself in a polling loop with TryEnterCriticalSection(), but that pretty much means you really should have used a mutex +wait instead.
    EnterCriticalSection blocks until the critical section becomes available. By waiting I guess you mean becomes signaled?

    Quote Originally Posted by OReubens View Post
    A critical section is also lighter weight than a mutex. (faster)
    Yes, but a critical section can't be used to sync resources shared between processes.

    Quote Originally Posted by OReubens View Post
    A named Mutex CAN be used accross processes, an unnamed mutex cannot.
    Sure it can, but you must pass the mutex handle to the 2nd process and use DuplicateHandle.

    Quote Originally Posted by OReubens View Post
    Ignoring the waitable feature, behaviourly a critical section and a mutex are similar and you could interchange them for most purposes. But from a design/semantic p.o.v. I personally won't ever use a critical section for anything other than guarding a "small" section of code where the lock/unlock happen in the same function (or in a contructor and matchign destructor). If I have a need for a lock in one place and the matching unlock in a totally different function, then I'd use a mutex.
    I've got auto-unlock wrappers for all my synchronization objects so using one type of sync object is pretty much the same as using another. I'll use a critical section to synchronize objects that I control within my process where I know there won't be any problem with the operation getting hung up. I'll use a mutex (with the timeout) for objects that are external and may need to be timed out (database, network operations, etc.).

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