當前位置: 首頁>>代碼示例>>Python>>正文


Python threading.RLock方法代碼示例

本文整理匯總了Python中threading.RLock方法的典型用法代碼示例。如果您正苦於以下問題:Python threading.RLock方法的具體用法?Python threading.RLock怎麽用?Python threading.RLock使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在threading的用法示例。


在下文中一共展示了threading.RLock方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: _checkLevel

# 需要導入模塊: import threading [as 別名]
# 或者: from threading import RLock [as 別名]
def _checkLevel(level):
    if isinstance(level, int):
        rv = level
    elif str(level) == level:
        if level not in _levelNames:
            raise ValueError("Unknown level: %r" % level)
        rv = _levelNames[level]
    else:
        raise TypeError("Level not an integer or a valid string: %r" % level)
    return rv

#---------------------------------------------------------------------------
#   Thread-related stuff
#---------------------------------------------------------------------------

#
#_lock is used to serialize access to shared data structures in this module.
#This needs to be an RLock because fileConfig() creates and configures
#Handlers, and so might arbitrary user threads. Since Handler code updates the
#shared dictionary _handlers, it needs to acquire the lock. But if configuring,
#the lock would already have been acquired - so we need an RLock.
#The same argument applies to Loggers and Manager.loggerDict.
# 
開發者ID:war-and-code,項目名稱:jawfish,代碼行數:25,代碼來源:__init__.py

示例2: __init__

# 需要導入模塊: import threading [as 別名]
# 或者: from threading import RLock [as 別名]
def __init__(self, autoescape=_DEFAULT_AUTOESCAPE, namespace=None,
                 whitespace=None):
        """構造一個模板加載器.

        :arg str autoescape: 在模板命名空間中的函數名, 例如 "xhtml_escape",
            或默認情況下為 ``None`` 來禁用自動轉義.
        :arg dict namespace: 一個被加入默認模板命名空間中的字典或 ``None``.
        :arg str whitespace: 一個指定模板中whitespace默認行為的字符串;
            參見 `filter_whitespace` 查看可選項. 默認是 "single" 對於
            ".html" 和 ".js" 文件的結束, "all" 是為了其他文件.

        .. versionchanged:: 4.3
           添加 ``whitespace`` 參數.
        """
        self.autoescape = autoescape
        self.namespace = namespace or {}
        self.whitespace = whitespace
        self.templates = {}
        # self.lock protects self.templates.  It's a reentrant lock
        # because templates may load other templates via `include` or
        # `extends`.  Note that thanks to the GIL this code would be safe
        # even without the lock, but could lead to wasted work as multiple
        # threads tried to compile the same template simultaneously.
        self.lock = threading.RLock() 
開發者ID:tao12345666333,項目名稱:tornado-zh,代碼行數:26,代碼來源:template.py

示例3: __init__

# 需要導入模塊: import threading [as 別名]
# 或者: from threading import RLock [as 別名]
def __init__(self, calls=15, period=900, clock=now(), raise_on_limit=True):
        '''
        Instantiate a RateLimitDecorator with some sensible defaults. By
        default the Twitter rate limiting window is respected (15 calls every
        15 minutes).

        :param int calls: Maximum function invocations allowed within a time period.
        :param float period: An upper bound time period (in seconds) before the rate limit resets.
        :param function clock: An optional function retuning the current time.
        :param bool raise_on_limit: A boolean allowing the caller to avoiding rasing an exception.
        '''
        self.clamped_calls = max(1, min(sys.maxsize, floor(calls)))
        self.period = period
        self.clock = clock
        self.raise_on_limit = raise_on_limit

        # Initialise the decorator state.
        self.last_reset = clock()
        self.num_calls = 0

        # Add thread safety.
        self.lock = threading.RLock() 
開發者ID:tomasbasham,項目名稱:ratelimit,代碼行數:24,代碼來源:decorators.py

示例4: __init__

# 需要導入模塊: import threading [as 別名]
# 或者: from threading import RLock [as 別名]
def __init__(self, serializer, input_data, chunk_size, string_max_len=None):
        super(IncrementalPandasToRecArraySerializer, self).__init__(serializer, input_data, chunk_size)
        if not isinstance(serializer, PandasSerializer):
            raise ArcticSerializationException("IncrementalPandasToRecArraySerializer requires a serializer of "
                                               "type PandasSerializer.")
        if not isinstance(input_data, (pd.DataFrame, pd.Series)):
            raise ArcticSerializationException("IncrementalPandasToRecArraySerializer requires a pandas DataFrame or "
                                               "Series as data source input.")
        if string_max_len and string_max_len < 1:
            raise ArcticSerializationException("IncrementalPandasToRecArraySerializer can't be initialized "
                                               "with string_max_len < 1 ({})".format(string_max_len))
        self.string_max_len = string_max_len
        # The state which needs to be lazily initialized
        self._dtype = None
        self._shape = None
        self._rows_per_chunk = 0
        self._total_chunks = 0
        self._has_string_object = False
        self._lock = RLock() 
開發者ID:man-group,項目名稱:arctic,代碼行數:21,代碼來源:incremental.py

示例5: __init__

# 需要導入模塊: import threading [as 別名]
# 或者: from threading import RLock [as 別名]
def __init__(self, pool_size):
        # Only allow creation via get_instance
        if not type(self)._SINGLETON_LOCK._is_owned():
            raise AsyncArcticException("{} is a singleton, can't create a new instance".format(type(self)))

        pool_size = int(pool_size)
        if pool_size < 1:
            raise ValueError("{} can't be instantiated with a pool_size of {}".format(type(self), pool_size))

        # Enforce the singleton pattern
        with type(self)._SINGLETON_LOCK:
            if type(self)._instance is not None:
                raise AsyncArcticException("LazySingletonTasksCoordinator is a singleton, can't create a new instance")
            self._lock = RLock()
            self._pool = None
            self._pool_size = int(pool_size)
            self._pool_update_hooks = []
            self.alive_tasks = {}
            self.is_shutdown = False 
開發者ID:man-group,項目名稱:arctic,代碼行數:21,代碼來源:_workers_pool.py

示例6: __init__

# 需要導入模塊: import threading [as 別名]
# 或者: from threading import RLock [as 別名]
def __init__(self, url, timeout=None, num_workers=10, **kwargs):
        """
        Initialise an instance.
        :param url: The root URL to use for scraping.
        :param timeout: The timeout, in seconds, to be applied to requests.
                        This defaults to ``None`` (no timeout specified).
        :param num_workers: The number of worker threads you want to do I/O,
                            This defaults to 10.
        :param kwargs: Passed to the superclass.
        """
        super(SimpleScrapingLocator, self).__init__(**kwargs)
        self.base_url = ensure_slash(url)
        self.timeout = timeout
        self._page_cache = {}
        self._seen = set()
        self._to_fetch = queue.Queue()
        self._bad_hosts = set()
        self.skip_externals = False
        self.num_workers = num_workers
        self._lock = threading.RLock()
        # See issue #45: we need to be resilient when the locator is used
        # in a thread, e.g. with concurrent.futures. We can't use self._lock
        # as it is for coordinating our internal threads - the ones created
        # in _prepare_threads.
        self._gplock = threading.RLock() 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:27,代碼來源:locators.py

示例7: __init__

# 需要導入模塊: import threading [as 別名]
# 或者: from threading import RLock [as 別名]
def __init__(self, app_yaml_path, backend_yaml_path):
    """Initializer for BackendsConfiguration.

    Args:
      app_yaml_path: A string containing the full path of the yaml file
          containing the configuration for this server.
      backend_yaml_path: A string containing the full path of the backends.yaml
          file containing the configuration for backends.
    """
    self._update_lock = threading.RLock()
    self._base_server_configuration = ServerConfiguration(app_yaml_path)
    backend_info_external = self._parse_configuration(
        backend_yaml_path)

    self._backends_name_to_backend_entry = {}
    for backend in backend_info_external.backends or []:
      self._backends_name_to_backend_entry[backend.name] = backend
    self._changes = dict(
        (backend_name, set())
        for backend_name in self._backends_name_to_backend_entry) 
開發者ID:elsigh,項目名稱:browserscope,代碼行數:22,代碼來源:application_configuration.py

示例8: acquire_lock

# 需要導入模塊: import threading [as 別名]
# 或者: from threading import RLock [as 別名]
def acquire_lock(self):
        """Acquire an exclusive lock on the currently-loaded session data."""
        self.locked = True
        self.locks.setdefault(self.id, threading.RLock()).acquire() 
開發者ID:cherrypy,項目名稱:cherrypy,代碼行數:6,代碼來源:sessions.py

示例9: __init__

# 需要導入模塊: import threading [as 別名]
# 或者: from threading import RLock [as 別名]
def __init__(self):
    self.a = 1
    self.b = 2
    self.rlock = threading.RLock() 
開發者ID:PacktPublishing,項目名稱:Learning-Concurrency-in-Python,代碼行數:6,代碼來源:rlocks.py

示例10: modifyA

# 需要導入模塊: import threading [as 別名]
# 或者: from threading import RLock [as 別名]
def modifyA(self):
    with self.rlock:
      print("Modifying A : RLock Acquired: {}".format(self.rlock._is_owned()))
      print("{}".format(self.rlock))
      self.a = self.a + 1
      time.sleep(5) 
開發者ID:PacktPublishing,項目名稱:Learning-Concurrency-in-Python,代碼行數:8,代碼來源:rlocks.py

示例11: modifyB

# 需要導入模塊: import threading [as 別名]
# 或者: from threading import RLock [as 別名]
def modifyB(self):
    with self.rlock:
      print("Modifying B : RLock Acquired: {}".format(self.rlock._is_owned()))
      print("{}".format(self.rlock))
      self.b = self.b - 1
      time.sleep(5) 
開發者ID:PacktPublishing,項目名稱:Learning-Concurrency-in-Python,代碼行數:8,代碼來源:rlocks.py

示例12: getlock

# 需要導入模塊: import threading [as 別名]
# 或者: from threading import RLock [as 別名]
def getlock(self, prefix):
        if prefix not in self.prefix_lock:
            self.prefix_lock[prefix] = RLock()
        return self.prefix_lock[prefix] 
開發者ID:sdn-ixp,項目名稱:iSDX,代碼行數:6,代碼來源:peer.py

示例13: getlock

# 需要導入模塊: import threading [as 別名]
# 或者: from threading import RLock [as 別名]
def getlock(self, prefixes):
        prefixes.sort()
        hsh = "-".join(prefixes)
        if hsh not in self.prefix_lock:
            #self.logger.debug("First Lock:: "+str(hsh))
            self.prefix_lock[hsh] = RLock()
        #else:
            #self.logger.debug("Repeat :: "+str(hsh))
        return self.prefix_lock[hsh] 
開發者ID:sdn-ixp,項目名稱:iSDX,代碼行數:11,代碼來源:participant_controller.py

示例14: __init__

# 需要導入模塊: import threading [as 別名]
# 或者: from threading import RLock [as 別名]
def __init__(self, filename, table_name='data', fast_save=False, **options):
        self.filename = filename
        self.table_name = table_name
        self.fast_save = fast_save
        self.can_commit = True
        self._bulk_commit = False
        self._pending_connection = None
        self._lock = threading.RLock()
        with self.connection() as con:
            con.execute("create table if not exists `%s` (key PRIMARY KEY, value)" % self.table_name) 
開發者ID:cgrok,項目名稱:clashroyale,代碼行數:12,代碼來源:utils.py

示例15: __init__

# 需要導入模塊: import threading [as 別名]
# 或者: from threading import RLock [as 別名]
def __init__(self, data=None, is_snapshot=False):
        if data is None:
            self._data = []
        else:
            self._data = data
        self._lock = threading.RLock()
        self._is_snapshot = is_snapshot 
開發者ID:jtolio,項目名稱:leveldb-py,代碼行數:9,代碼來源:leveldb.py


注:本文中的threading.RLock方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。