是否有相当于 C++ 的东西? Python线程中的lock_guard?

发布于 2025-01-12 19:26:31 字数 798 浏览 1 评论 0原文

从 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 技术交流群。

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

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文