标签:str different date for already tran sam may can
# -*- 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
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
标签:str different date for already tran sam may can
原文地址:https://www.cnblogs.com/yuanjiangw/p/11838399.html