我可以嵌套关键部分吗? TCriticalSection 可以嵌套吗?

发布于 2024-09-18 02:19:11 字数 378 浏览 4 评论 0原文

我想要两个过程可以相互调用,或者从正在运行的任何线程调用,但一次只能运行一个。我该怎么做?这能正常工作吗?

var
  cs: TCriticalSection;

procedure a;
begin
  cs.Acquire;
  try
    // Execute single threaded here. 
  finally
    cs.Release;
  end;
end;

procedure b;
begin
  cs.Acquire;
  try
    // Execute single threaded here. Maybe with calls to procedure a.
  finally
    cs.Release;
  end;
end;

I want to have two procedures which can call each other, or be called from whatever threads are running, but only have one running at a time. How can I do this? Will this work correctly?

var
  cs: TCriticalSection;

procedure a;
begin
  cs.Acquire;
  try
    // Execute single threaded here. 
  finally
    cs.Release;
  end;
end;

procedure b;
begin
  cs.Acquire;
  try
    // Execute single threaded here. Maybe with calls to procedure a.
  finally
    cs.Release;
  end;
end;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

暖风昔人 2024-09-25 02:19:40

虽然在 Windows 上可以多次获取关键部分,但不可能在所有平台上,其中一些平台会阻止尝试重新获取同步对象。

这里实际上没有必要允许“嵌套”。如果你正确地设计你的类,公共接口获取和释放关键部分,而实现方法则不然,并且如果你确保实现方法永远不会调用接口方法,那么你就不需要那个特定的方法。特征。

另请参阅堆栈溢出问题“递归锁(互斥锁)与非递归锁Lock (Mutex)” 了解递归互斥体/关键部分获取的缺点的一些详细信息。

While it is possible on Windows to acquire a critical section multiple times, it is not possible on all platforms, some of them will block on the attempt to re-acquire a synchronization object.

There is not really a need to allow for "nesting" here. If you design your classes properly, in a way that the public interface acquires and releases the critical section, and the implementation methods don't, and if you make sure that implementation methods never call interface methods, then you don't need that particular feature.

See also the Stack Overflow question "Recursive Lock (Mutex) vs Non-Recursive Lock (Mutex)" for some details on the bad sides of recursive mutex / critical section acquisition.

吻风 2024-09-25 02:19:32

是的,那会起作用的。在同一线程中,过程 A 可以调用过程 B,反之亦然,当线程 A 使用过程 A 或过程 B 时,线程 B 在想要使用这些过程时必须等待。

请参阅有关关键部分的 MSDN 文档: http://msdn .microsoft.com/en-us/library/ms682530%28VS.85%29.aspx

关键部分可以嵌套,但对于每次调用 Acquire 都必须调用 Release。因为您在 try ..finally 子句中进行了 Release 调用,所以您可以确保这种情况发生,因此您的代码没有问题。

Yes, that will work. Procedure A can call B and vice versa within the same thread and while Thread A is using procedure A or B, Thread B has to wait when it wants to use those procedures.

See the MSDN documentation about Critical Sections: http://msdn.microsoft.com/en-us/library/ms682530%28VS.85%29.aspx

Critical sections can be nested, but for every call to Acquire you must have a call to Release. Because you have your Release call in a try .. finally clause you ensure that this happens, so your code is fine.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文