Older Newer
Sat, 05 Jul 2008 10:51:45 . . . . afh [returns false if hCS = 0]


Changes by last author:

Added:
= 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.

<code>

</code>

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

== Example[[Anchor 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.

<code>

//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

}

</code>

== Also see ==

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

== Comments ==

:Everyone can add his or her comments about his or her experiences with this function. Tips for using it are welcome, too.