Question

I'm not sure if I correctly understand. TryEnterCriticalSection is called only once, it's not stick like EnterCriticalSection? E.g. if I write something like

if(TryEnterCriticalSection (&cs))
{
//do something that must be synh
LeaveCriticalSection(&cs);
}
else
{
//do other job
}
//go on

and if TryEnterCriticalSection returns false the part do something that must be synh will never be done, and do other job part will be exucuted and then go on?

Was it helpful?

Solution

You guessed right. TryEnterCriticalSection() is called once, and tries to enter the critical section only once. If the critical section is locked, it returns false after the check.

In general, if a function returns a boolean or an int, the if/else clauses behaves like following:

if (function()) //function() is called once here, return result is checked
{
  //executed if function() returned true or non-zero
}
else
{
  //executed if function() returned false or zero
}
//executed whatever happens

OTHER TIPS

TryEnterCriticalSection() does the following:

  • tries to enter a critical section
  • if that section is currently grabbed by some other thread the section is not entered and the function returns zero, otherwise
  • the section is entered and the function returns nonzero

Anyway the function never blocks. Compare it with EnterCriticalSection() that falls through if no other thread has the critical section entered and blocks if such other thread exists.

So the outcome of your code will depend on whether the critical section is entered by another thread at the moment the function is called. Don't forget to call LeaveCriticalSection() for each time when TryEnterCriticalSection() returns nonzero (succeeds).

So yes, your code is written with right assumptions.

Yes, your code is correct.

See more on MSDN.

If your critical section is too small, than you must try this TryEnterCriticalSection in a loop because it will then acquire less clock cycles to enter critical section and leave that critical section.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top