我可以嵌套关键部分吗? TCriticalSection 可以嵌套吗?
我想要两个过程可以相互调用,或者从正在运行的任何线程调用,但一次只能运行一个。我该怎么做?这能正常工作吗?
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
虽然在 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.
是的,那会起作用的。在同一线程中,过程 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.