tryEnterCriticalSection

Syntax

bool tryEnterCriticalSection(int hCS)

Arguments

hCS
Specifies the handle of the Critical Section to be entered, as obtained by a call to createCriticalSection.

Return

Returns true if the Critical Section was successfully entered, false if another thread already owns the Critical Section or if hCS is zero.

Description

This function is similar to enterCriticalSection, but does not wait if another thread already owns the designated Critical Section--in which case it returns immediately with a return value of false. This allows the calling thread to perform other useful work instead of blocking while the Critical Section is busy.

For more information about Critical Sections, see the MSDN documentation about [Critical Section Objects].

Example

In the following somewhat contrived example, myThreadFunction uses a Critical Section (myCS) to serialize access to myGlobalFlag. However, if the current thread cannot gain immediate access to the Critical Section via tryEnterCriticalSection, it goes off for a while (no pun intended) to perform some other useful work (perhaps updating the GUI) before retrying entry to the Critical Section. Note that we call sleep(0) at the end of the while-loop to voluntarily yield the rest of our timeslice so another ready thread may be able to run, rather than hogging an entire timeslice unnecessarily.

    //global variables
    int myGlobalFlag = 0;
    int myCS = createCriticalSection();

    int myThreadFunction(void) {
        while (!tryEnterCriticalSection(myCS)) {
            // do some other useful work here...
            sleep(0); //give up timeslice
        }
        //we have now entered the Critical Section
        //guarding access to myGlobalFlag...
        if (myGlobalFlag==0) {
            myGlobalFlag = 1;
            //do something...
            myGlobalFlag = 0;
        }
        leaveCriticalSection(myCS);
        return 0; //exit code
    }

See Also

System Functions, Critical Section Functions, createCriticalSection, enterCriticalSection, leaveCriticalSection, deleteCriticalSection