码迷,mamicode.com
首页 > 编程语言 > 详细

https://github.com/python/cpython/blob/master/Doc/library/contextlib.rst

时间:2019-11-11 21:50:22      阅读:84      评论:0      收藏:0      [点我收藏+]

标签: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

 

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!