本文整理汇总了Python中threading.Thread方法的典型用法代码示例。如果您正苦于以下问题:Python threading.Thread方法的具体用法?Python threading.Thread怎么用?Python threading.Thread使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类threading
的用法示例。
在下文中一共展示了threading.Thread方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: download_all_section
# 需要导入模块: import threading [as 别名]
# 或者: from threading import Thread [as 别名]
def download_all_section(*arg):
if len(arg)==1:
k=arg[0]
th=[]
for key in decode.keys():
th.append(threading.Thread(target=download, args=(key,k)))
for t in th:
t.start()
for t in th:
t.join()
elif len(arg)==2:
From=arg[0]
To=arg[1]
th=[]
for key in decode.keys():
th.append(threading.Thread(target=download, args=(key, From, To)))
for t in th:
t.start()
for t in th:
t.join()
示例2: auto
# 需要导入模块: import threading [as 别名]
# 或者: from threading import Thread [as 别名]
def auto(self, start_message, end_message):
"""
Auto progress.
"""
self._auto_running = threading.Event()
self._auto_thread = threading.Thread(target=self._spin)
self.start(start_message)
self._auto_thread.start()
try:
yield self
except (Exception, KeyboardInterrupt):
self._io.write_line("")
self._auto_running.set()
self._auto_thread.join()
raise
self.finish(end_message, reset_indicator=True)
示例3: parallel_download_all_section
# 需要导入模块: import threading [as 别名]
# 或者: from threading import Thread [as 别名]
def parallel_download_all_section(*arg):
if len(arg)==1:
k=arg[0]
pro=[]
for key in decode.keys():
pro.append(multiprocessing.Process(target=download, args=(key, k)))
#th.append(threading.Thread(target=download, args=(key,k)))
for p in pro:
p.start()
for p in pro:
p.join()
elif len(arg)==2:
From=arg[0]
To=arg[1]
pro=[]
for key in decode.keys():
pro.append(multiprocessing.Process(target=download, args=(key, From, To)))
#th.append(threading.Thread(target=download, args=(key,k)))
for p in pro:
p.start()
for p in pro:
p.join()
示例4: test_task_complete
# 需要导入模块: import threading [as 别名]
# 或者: from threading import Thread [as 别名]
def test_task_complete(self, deckhand_ingester, input_files, setup,
blank_state, mock_get_build_data):
input_file = input_files.join("deckhand_fullsite.yaml")
design_ref = "file://%s" % str(input_file)
orchestrator = orch.Orchestrator(
state_manager=blank_state, ingester=deckhand_ingester)
orch_task = orchestrator.create_task(
action=hd_fields.OrchestratorAction.Noop, design_ref=design_ref)
orch_task.set_status(hd_fields.TaskStatus.Queued)
orch_task.save()
orch_thread = threading.Thread(target=orchestrator.watch_for_tasks)
orch_thread.start()
try:
time.sleep(10)
orch_task = blank_state.get_task(orch_task.get_id())
assert orch_task.get_status() == hd_fields.TaskStatus.Complete
finally:
orchestrator.stop_orchestrator()
orch_thread.join(10)
示例5: get_task_status
# 需要导入模块: import threading [as 别名]
# 或者: from threading import Thread [as 别名]
def get_task_status(id):
"""Query the status of an asynchronous task."""
# obtain the task and validate it
global background_tasks
rv = background_tasks.get(id)
if rv is None:
return not_found(None)
# if the task object is a Thread object that means that the task is still
# running. In this case return the 202 status message again.
if isinstance(rv, Thread):
return jsonify({}), 202, {'Location': url_for('get_task_status', id=id)}
# If the task object is not a Thread then it is assumed to be the response
# of the finished task, so that is the response that is returned.
# If the application is configured to auto-delete task status resources once
# the task is done then the deletion happens now, if not the client is
# expected to send a delete request.
if app.config['AUTO_DELETE_BG_TASKS']:
del background_tasks[id]
return rv
示例6: __init__
# 需要导入模块: import threading [as 别名]
# 或者: from threading import Thread [as 别名]
def __init__(self, eventHandler):
threading.Thread.__init__(self)
self.name = 'Server'
self.daemon = True
self._eventHandler = eventHandler
self._client = None
self._server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try:
self._server.bind(('', PORT))
self._server.listen(5)
except socket.error:
event = Event(Events.SCAN_ERROR, msg='Could not start server')
post_event(eventHandler, event)
return
self._cancel = False
self.start()
示例7: __init__
# 需要导入模块: import threading [as 别名]
# 或者: from threading import Thread [as 别名]
def __init__(self, eventHandler, freq, gain, cal):
threading.Thread.__init__(self)
self.name = 'Receive'
self.daemon = True
self._cancel = False
self._freq = freq
self._gain = gain
self._cal = cal
self._eventHandler = eventHandler
self._sdr = None
self._capture = (ctypes.c_ubyte * SAMPLES)()
devices = rtlsdr.librtlsdr.rtlsdr_get_device_count()
if devices == 0:
event = Event(Events.SCAN_ERROR, msg='No device found')
post_event(eventHandler, event)
else:
self.start()
示例8: start_with_callback
# 需要导入模块: import threading [as 别名]
# 或者: from threading import Thread [as 别名]
def start_with_callback(self, func, args=None, kwargs=None):
"""Start 'func' in a new thread T, then start self (and return T)."""
if args is None:
args = ()
if kwargs is None:
kwargs = {}
args = (func,) + args
def _callback(func, *a, **kw):
self.wait(states.STARTED)
func(*a, **kw)
t = threading.Thread(target=_callback, args=args, kwargs=kwargs)
t.setName('Bus Callback ' + t.getName())
t.start()
self.start()
return t
示例9: start
# 需要导入模块: import threading [as 别名]
# 或者: from threading import Thread [as 别名]
def start(self):
"""Start the HTTP server."""
if self.running:
self.bus.log('Already serving on %s' % self.description)
return
self.interrupt = None
if not self.httpserver:
raise ValueError('No HTTP server has been created.')
if not os.environ.get('LISTEN_PID', None):
# Start the httpserver in a new thread.
if isinstance(self.bind_addr, tuple):
portend.free(*self.bind_addr, timeout=Timeouts.free)
import threading
t = threading.Thread(target=self._start_http_thread)
t.setName('HTTPServer ' + t.getName())
t.start()
self.wait()
self.running = True
self.bus.log('Serving on %s' % self.description)
示例10: test_wait
# 需要导入模块: import threading [as 别名]
# 或者: from threading import Thread [as 别名]
def test_wait(bus):
"""Test that bus wait awaits for states."""
def f(method): # pylint: disable=invalid-name
time.sleep(0.2)
getattr(bus, method)()
flow = [
('start', [bus.states.STARTED]),
('stop', [bus.states.STOPPED]),
('start', [bus.states.STARTING, bus.states.STARTED]),
('exit', [bus.states.EXITING]),
]
for method, states in flow:
threading.Thread(target=f, args=(method,)).start()
bus.wait(states)
# The wait method MUST wait for the given state(s).
assert bus.state in states, 'State %r not in %r' % (bus.state, states)
示例11: test_8_Ram_Cleanup
# 需要导入模块: import threading [as 别名]
# 或者: from threading import Thread [as 别名]
def test_8_Ram_Cleanup(self):
def lock():
s1 = sessions.RamSession()
s1.acquire_lock()
time.sleep(1)
s1.release_lock()
t = threading.Thread(target=lock)
t.start()
start = time.time()
while not sessions.RamSession.locks and time.time() - start < 5:
time.sleep(0.01)
assert len(sessions.RamSession.locks) == 1, 'Lock not acquired'
s2 = sessions.RamSession()
s2.clean_up()
msg = 'Clean up should not remove active lock'
assert len(sessions.RamSession.locks) == 1, msg
t.join()
示例12: main
# 需要导入模块: import threading [as 别名]
# 或者: from threading import Thread [as 别名]
def main():
print("Starting number crunching")
t0 = time.time()
threads = []
for i in range(10):
thread = threading.Thread(target=executeProc)
threads.append(thread)
thread.start()
for thread in threads:
thread.join()
t1 = time.time()
totalTime = t1 - t0
print("Execution Time: {}".format(totalTime))
示例13: run
# 需要导入模块: import threading [as 别名]
# 或者: from threading import Thread [as 别名]
def run(self):
"""
Thread run method. Consumes integers from list
"""
while True:
self.condition.acquire()
print 'condition acquired by %s' % self.name
while True:
if self.integers:
integer = self.integers.pop()
print '%d popped from list by %s' % (integer, self.name)
break
print 'condition wait by %s' % self.name
self.condition.wait()
print 'condition released by %s' % self.name
self.condition.release()
示例14: start
# 需要导入模块: import threading [as 别名]
# 或者: from threading import Thread [as 别名]
def start(self):
logger.info("Starting the BGP PctrlListener")
while self.run:
conn = self.listener.accept()
pc = PctrlClient(conn, self.listener.last_accepted)
t = Thread(target=pc.start)
with clientPoolLock:
logger.debug('Trace: PctrlListener.start: clientActivePool before: %s', clientActivePool)
logger.debug('Trace: PctrlListener.start: clientDeadPool before: %s', clientDeadPool)
clientActivePool[pc] = t
# while here, join dead threads.
while clientDeadPool:
clientDeadPool.pop().join()
logger.debug('Trace: PctrlListener.start: clientActivePool after: %s', clientActivePool)
logger.debug('Trace: PctrlListener.start: clientDeadPool after: %s', clientDeadPool)
t.start()
示例15: start_eh_arp
# 需要导入模块: import threading [as 别名]
# 或者: from threading import Thread [as 别名]
def start_eh_arp(self):
self.logger.info("ARP Event Handler started.")
while self.run:
# need to poll since recv() will not detect close from this end
# and need some way to shutdown gracefully.
if not self.arp_client.poll(1):
continue
try:
tmp = self.arp_client.recv()
except EOFError:
break
data = json.loads(tmp)
self.logger.debug("ARP Event received: %s", data)
# Starting a thread for independently processing each incoming network event
event_processor_thread = Thread(target=self.process_event, args=(data,))
event_processor_thread.daemon = True
event_processor_thread.start()
self.arp_client.close()
self.logger.debug("Exiting start_eh_arp")