Reputation: 2316
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
?
Upvotes: 4
Views: 6954
Reputation: 1
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.
Upvotes: 0
Reputation: 90296
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
Upvotes: 2
Reputation: 170489
TryEnterCriticalSection()
does the following:
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.
Upvotes: 6