是否有相当于 C++ 的东西? Python线程中的lock_guard?
从 C++ 开始使用 Python 线程库。
C++ 中有一个名为 lock_guard 的类,其中对象控制提供的锁,然后销毁lock_guard对象&在退出创建 lock_guard 的范围时释放锁。
经过一些研究后,似乎使用 with
语句 使用 Lock
对象在上下文管理器的控制下创建运行时上下文可能是最接近的等价物。所以,像这样...
myLock = threading.Lock()
with myLock:
# My critical region here ...
我的理解是 with
语句将在退出时释放锁,与 C++ lock_guard 类似。
这是到的正确映射吗?制作?如果不是,那么与 Python 线程库中的 lock_guard
更好的等效项是什么?如果是这样,我在这里缺少什么细微差别吗?
Beginning to work with the Python threading library after coming from C++.
There exists a class in C++ called a lock_guard, in which the object takes control of a provided lock, and then destructs the lock_guard object & releases the lock upon exit of the scope in which the lock_guard was created.
After doing some research, it appears that using a with
statement with a Lock
object to create a runtime context under the control of a context manager may be the closest equivalent. So, something like this...
myLock = threading.Lock()
with myLock:
# My critical region here ...
My understanding is that the with
statement will release the lock upon exit, in similar fashion to a C++ lock_guard.
Is this a correct mapping to make? If not, what is a better equivalent to a lock_guard
in Python's threading library? And if so, is there nuance I am missing here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论