本文整理汇总了Python中threading.Lock方法的典型用法代码示例。如果您正苦于以下问题:Python threading.Lock方法的具体用法?Python threading.Lock怎么用?Python threading.Lock使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类threading
的用法示例。
在下文中一共展示了threading.Lock方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: import threading [as 别名]
# 或者: from threading import Lock [as 别名]
def __init__(self, maxsize = 0, worker_threads = 1, unpack_threads = 1, inspect_threads = 1, idb_threads = 1, bindiff_threads = 1):
"""
Create a Bass server.
:param maxsize: Maximum size of the job queue. If the queue is full, jobs are rejected. 0 means unlimited.
:param threads: Number of worker threads to use.
"""
#TODO: Access to jobs is not threadsafe
self.job_counter = 1
self.jobs = {}
self.jobs_lock = Lock()
self.input_queue = Queue(maxsize)
self.unpack_executor = ThreadPoolExecutor(max_workers = unpack_threads)
self.inspect_executor = ThreadPoolExecutor(max_workers = inspect_threads)
self.idb_executor = ThreadPoolExecutor(max_workers = idb_threads)
self.bindiff_executor = ThreadPoolExecutor(max_workers = bindiff_threads)
self.inspectors = [MagicInspector(), SizeInspector(), FileTypeInspector()]
self.terminate = False
self.threads = [start_thread(self.process_job) for _ in range(worker_threads)]
self.bindiff = BindiffClient(urls = [BINDIFF_SERVICE_URL])
self.whitelist = FuncDB(FUNCDB_SERVICE_URL)
self.ida = IdaClient(urls = [IDA_SERVICE_URL])
示例2: main
# 需要导入模块: import threading [as 别名]
# 或者: from threading import Lock [as 别名]
def main():
print("Starting our Web Crawler")
baseUrl = input("Website > ")
numberOfThreads = input("No Threads > ")
linksToCrawl = queue.Queue()
urlLock = threading.Lock()
linksToCrawl.put(baseUrl)
haveVisited = []
crawlers = []
errorLinks = []
for i in range(int(numberOfThreads)):
crawler = Crawler(baseUrl, linksToCrawl, haveVisited, errorLinks, urlLock)
crawler.start()
crawlers.append(crawler)
for crawler in crawlers:
crawler.join()
print("Total Number of Pages Visited {}".format(len(haveVisited)))
print("Total Number of Pages with Errors {}".format(len(errorLinks)))
示例3: __init__
# 需要导入模块: import threading [as 别名]
# 或者: from threading import Lock [as 别名]
def __init__(self, open):
"""
A class that encapsulates a FileSystemWatcher over SMB. It is designed to make it easy to run the watcher in
the background and provide an event that is fired when the server notifies that a change has occurred. It is
up to the caller to action on that event through their own sync or asynchronous implementation.
:param open: The Open() class of a directory to watch for change notifications.
"""
self.open = open
self.response_event = threading.Event()
self._t_on_response = threading.Thread(target=self._on_response)
self._t_on_response.daemon = True
self._t_exc = None
self._request = None
self._file_actions = None
self._result_lock = threading.Lock() # Used to ensure the result is only processed once
示例4: send
# 需要导入模块: import threading [as 别名]
# 或者: from threading import Lock [as 别名]
def send(self, msg_id, params=None, token=None):
if msg_id not in self.session.locks:
self.session.locks[msg_id] = threading.Lock()
print("[LOCK] ", msg_id)
if self.session.locks[msg_id].locked():
return 0
else:
self.session.locks[msg_id].acquire()
if token is None:
token = self.session.token
payload = self.create_payload(msg_id, token, params)
data = json.dumps(payload).encode()
print(data)
timediff = time.time() - self.last_send
if timediff < 0.5:
time.sleep(0.5 - timediff)
self.last_send = time.time()
return self.socket.send(data)
示例5: __init__
# 需要导入模块: import threading [as 别名]
# 或者: from threading import Lock [as 别名]
def __init__(self, scope_manager=None):
"""Initialize a MockTracer instance."""
scope_manager = ThreadLocalScopeManager() \
if scope_manager is None else scope_manager
super(MockTracer, self).__init__(scope_manager)
self._propagators = {}
self._finished_spans = []
self._spans_lock = Lock()
# Simple-as-possible (consecutive for repeatability) id generation.
self._next_id = 0
self._next_id_lock = Lock()
self._register_required_propagators()
示例6: __init__
# 需要导入模块: import threading [as 别名]
# 或者: from threading import Lock [as 别名]
def __init__(
self,
tracer,
operation_name=None,
context=None,
parent_id=None,
tags=None,
start_time=None):
super(MockSpan, self).__init__(tracer, context)
self._tracer = tracer
self._lock = Lock()
self.operation_name = operation_name
self.start_time = start_time
self.parent_id = parent_id
self.tags = tags if tags is not None else {}
self.finish_time = -1
self.finished = False
self.logs = []
示例7: test_initialization
# 需要导入模块: import threading [as 别名]
# 或者: from threading import Lock [as 别名]
def test_initialization():
baseplate = Lego.start(None, threading.Lock())
baseplate_proxy = baseplate.proxy()
baseplate_proxy.add_child(IRC, # nosec
channels=['#foo'],
nickname='test_nick',
server='foo.testing',
port=6667,
use_ssl=False,
username='test_username',
password='test_password')
# Cleanup
children = baseplate_proxy.children.get()
for child in children:
child.stop()
baseplate.stop()
示例8: __init__
# 需要导入模块: import threading [as 别名]
# 或者: from threading import Lock [as 别名]
def __init__(
self, baseplate, lock: threading.Lock, log_file=None, acl=None):
"""
:param baseplate: the baseplate Lego, which should be \
the same instance of Lego for all Legos
:param lock: a threading lock, which should be the same \
instance of threading.Lock for all Legos
"""
super().__init__()
if not lock:
raise LegoError("Lock expected but not provided!")
self.baseplate = baseplate
self.children = []
self.lock = lock
self.log_file = log_file
self.acl = acl
示例9: __init__
# 需要导入模块: import threading [as 别名]
# 或者: from threading import Lock [as 别名]
def __init__(self, reactor):
self.reactor = reactor
self.updateLock = threading.Lock()
self.updateQueue = []
# Map update_id -> update object.
self.active_changes = {}
# TODO: Ideally, load this from file so that change IDs are unique
# across system reboots.
self.next_change_id = 1
###########################################################################################
# Launch the first update call, NOTE that you have to use callInThread!!
# This happens because the perform_updates should run in its own thread,
# it makes blocking calls and such... so if we *don't* use callInThread
# then this function WILL BLOCK THE MAIN EVENT LOOP (ie. you cannot send any data)
#
# FIXME: It should be noted that calling updateLock.acquire(), e.g.
# from add_update, also blocks the main thread. Synchronizing access
# to the work queue should be reworked.
###########################################################################################
self.reactor.callInThread(self._perform_updates)
示例10: __init__
# 需要导入模块: import threading [as 别名]
# 或者: from threading import Lock [as 别名]
def __init__(self, buffer_shapes, size_in_transitions, T, sample_transitions):
"""Creates a replay buffer.
Args:
buffer_shapes (dict of ints): the shape for all buffers that are used in the replay
buffer
size_in_transitions (int): the size of the buffer, measured in transitions
T (int): the time horizon for episodes
sample_transitions (function): a function that samples from the replay buffer
"""
self.buffer_shapes = buffer_shapes
self.size = size_in_transitions // T
self.T = T
self.sample_transitions = sample_transitions
# self.buffers is {key: array(size_in_episodes x T or T+1 x dim_key)}
self.buffers = {key: np.empty([self.size, *shape])
for key, shape in buffer_shapes.items()}
# memory management
self.current_size = 0
self.n_transitions_stored = 0
self.lock = threading.Lock()
示例11: __init__
# 需要导入模块: import threading [as 别名]
# 或者: from threading import Lock [as 别名]
def __init__(self, config: CosmosDbPartitionedConfig):
"""Create the storage object.
:param config:
"""
super(CosmosDbPartitionedStorage, self).__init__()
self.config = config
self.client = None
self.database = None
self.container = None
self.compatability_mode_partition_key = False
# Lock used for synchronizing container creation
self.__lock = Lock()
if config.key_suffix is None:
config.key_suffix = ""
if not config.key_suffix.__eq__(""):
if config.compatibility_mode:
raise Exception(
"compatibilityMode cannot be true while using a keySuffix."
)
suffix_escaped = CosmosDbKeyEscape.sanitize_key(config.key_suffix)
if not suffix_escaped.__eq__(config.key_suffix):
raise Exception(
f"Cannot use invalid Row Key characters: {config.key_suffix} in keySuffix."
)
示例12: __init__
# 需要导入模块: import threading [as 别名]
# 或者: from threading import Lock [as 别名]
def __init__(self, freq = 100.0):
EventDispatcher2.state_lock.acquire()
if EventDispatcher2.ed_inum != 0:
EventDispatcher2.state_lock.release()
raise StdException('BZZZT, EventDispatcher2 has to be singleton!')
EventDispatcher2.ed_inum = 1
EventDispatcher2.state_lock.release()
self.tcbs_lock = Lock()
self.tlisteners = []
self.slisteners = []
self.signals_pending = []
self.last_ts = MonoTime()
self.my_ident = get_ident()
self.elp = ElPeriodic(freq)
self.elp.CFT_enable(signal.SIGURG)
self.bands = [(freq, 0),]
示例13: __init__
# 需要导入模块: import threading [as 别名]
# 或者: from threading import Lock [as 别名]
def __init__(self, maxsize=0):
self.maxsize = maxsize
self._init(maxsize)
# mutex must be held whenever the queue is mutating. All methods
# that acquire mutex must release it before returning. mutex
# is shared between the three conditions, so acquiring and
# releasing the conditions also acquires and releases mutex.
self.mutex = _threading.Lock()
# Notify not_empty whenever an item is added to the queue; a
# thread waiting to get is notified then.
self.not_empty = _threading.Condition(self.mutex)
# Notify not_full whenever an item is removed from the queue;
# a thread waiting to put is notified then.
self.not_full = _threading.Condition(self.mutex)
# Notify all_tasks_done whenever the number of unfinished tasks
# drops to zero; thread waiting to join() is notified to resume
self.all_tasks_done = _threading.Condition(self.mutex)
self.unfinished_tasks = 0
示例14: __init__
# 需要导入模块: import threading [as 别名]
# 或者: from threading import Lock [as 别名]
def __init__(self, maxsize=0):
self.maxsize = maxsize
self._init(maxsize)
# mutex must be held whenever the queue is mutating. All methods
# that acquire mutex must release it before returning. mutex
# is shared between the three conditions, so acquiring and
# releasing the conditions also acquires and releases mutex.
self.mutex = threading.Lock()
# Notify not_empty whenever an item is added to the queue; a
# thread waiting to get is notified then.
self.not_empty = threading.Condition(self.mutex)
# Notify not_full whenever an item is removed from the queue;
# a thread waiting to put is notified then.
self.not_full = threading.Condition(self.mutex)
# Notify all_tasks_done whenever the number of unfinished tasks
# drops to zero; thread waiting to join() is notified to resume
self.all_tasks_done = threading.Condition(self.mutex)
self.unfinished_tasks = 0
示例15: __init__
# 需要导入模块: import threading [as 别名]
# 或者: from threading import Lock [as 别名]
def __init__(self,visuals,datasource,**kwargs):
Chart.__init__(self,visuals,datasource,**kwargs)
self.layout.overflow = "auto"
if self.hasOpt("image") == False:
raise Exception("you must specify the image property")
self._entries = {}
self._lock = threading.Lock()
self._imageWidth = self.getOpt("image_width",300)
self._imageHeight = self.getOpt("image_height",300)
orientation = self.getOpt("orientation","vertical")
if orientation == "horizontal":
self.layout.width = self.getOpt("width","800px")
self.layout.height = str(self._imageHeight + 100) + "px"
else:
self.layout.width = str(self._imageWidth + 80) + "px"
self.layout.height = self.getOpt("height","800px")
self._detection = None