尝试进入关键部分
我不确定我的理解是否正确。 TryEnterCriticalSection
只调用一次,它不像 EnterCriticalSection
那样粘住? 例如,如果我写类似的内容
if(TryEnterCriticalSection (&cs))
{
//do something that must be synh
LeaveCriticalSection(&cs);
}
else
{
//do other job
}
//go on
,并且如果 TryEnterCriticalSection
返回 false,则 do某些必须是 synh
的部分将永远不会完成,而do other job
部分将被执行然后继续
?
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
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
TryEnterCriticalSection()
执行以下操作:无论如何,该函数永远不会阻塞。将其与 EnterCriticalSection() 进行比较,如果没有其他线程进入临界区,则 EnterCriticalSection() 会失败,如果存在其他线程,则阻塞。
因此,代码的结果将取决于调用函数时另一个线程是否进入临界区。不要忘记每次
TryEnterCriticalSection()
返回非零(成功)时调用LeaveCriticalSection()
。所以是的,您的代码是在正确的假设下编写的。
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 whenTryEnterCriticalSection()
returns nonzero (succeeds).So yes, your code is written with right assumptions.
你猜对了。
TryEnterCriticalSection()
被调用一次,并且仅尝试进入临界区一次。如果临界区被锁定,则检查后返回false。一般来说,如果函数返回布尔值或 int,则 if/else 子句的行为如下:
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:
是的,您的代码是正确的。
有关详细信息,请参阅 MSDN。
Yes, your code is correct.
See more on MSDN.
如果您的临界区太小,则必须在循环中尝试此
TryEnterCriticalSection
,因为这样它将获取更少的时钟周期来进入临界区并离开该临界区。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.