Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TryEnterCriticalSection

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?

like image 417
Alecs Avatar asked Feb 23 '23 11:02

Alecs


1 Answers

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.

like image 173
sharptooth Avatar answered Mar 07 '23 23:03

sharptooth