https://github.com/python/cpython/blob/master/Doc/library/contextlib.rst
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了https://github.com/python/cpython/blob/master/Doc/library/contextlib.rst,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2067字,纯文字阅读大概需要3分钟。
内容图文
# -*- coding: utf-8 -*- import time from threading import Lock, RLock from datetime import datetime from threading import Thread import threading class Test: def __init__(self): self.obj_lock = Lock() self.obj_rlock = RLock() self.a = 1 self.b = 2 self.r = 'r' def t(self): print('123') def a(self): with self.obj_lock: print("a") self.b() def b(self): with self.obj_lock: print("b") def ar(self): with self.obj_rlock: print("ar") self.r = 'ar' self.br() def br(self): with self.obj_rlock: print("br") self.r = 'br' t = Test() print(t.a) t.t() t.ar() # t.br() print('t.r', t.r)
https://github.com/python/cpython/blob/master/Doc/library/contextlib.rst
https://github.com/python/cpython/blob/master/Doc/library/contextlib.rst#reentrant-context-managers
Reentrant context managers
More sophisticated context managers may be "reentrant". These context managers can not only be used in multiple :keyword:`with` statements, but may also be used inside a :keyword:`!with` statement that is already using the same context manager.
:class:`threading.RLock` is an example of a reentrant context manager, as are :func:`suppress` and :func:`redirect_stdout`. Here's a very simple example of reentrant use:
>>> from contextlib import redirect_stdout >>> from io import StringIO >>> stream = StringIO() >>> write_to_stream = redirect_stdout(stream) >>> with write_to_stream: ... print("This is written to the stream rather than stdout") ... with write_to_stream: ... print("This is also written to the stream") ... >>> print("This is written directly to stdout") This is written directly to stdout >>> print(stream.getvalue()) This is written to the stream rather than stdout This is also written to the stream
Real world examples of reentrancy are more likely to involve multiple functions calling each other and hence be far more complicated than this example.
Note also that being reentrant is not the same thing as being thread safe. :func:`redirect_stdout`, for example, is definitely not thread safe, as it makes a global modification to the system state by binding :data:`sys.stdout` to a different stream.
内容总结
以上是互联网集市为您收集整理的https://github.com/python/cpython/blob/master/Doc/library/contextlib.rst全部内容,希望文章能够帮你解决https://github.com/python/cpython/blob/master/Doc/library/contextlib.rst所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。