python自定义线程池控制线程数量的示例
1.自定义线程池
import threading import Queue import time queue = Queue.Queue() def put_data_in_queue(): for i in xrange(10): queue.put(i) class MyThread(threading.Thread): def run(self): while not queue.empty(): sleep_times = queue.get() time.sleep(sleep_times) queue.task_done() def main_function(): threads_num = 6 while True: put_data_in_queue() for i in xrange(threads_num): myThread = MyThread() myThread.setDaemon(True) myThread.start() queue.join() time.sleep(60)
2.多线程与signal信号的监控结合
import threading import Queue import time import signal queue = Queue.Queue() stop = False def receive_signal(signum, stack): signal.signal(signal.SIGTERM, original_sigterm) global stop stop = True def put_data_in_queue(): for i in xrange(10): queue.put(i) class MyThread(threading.Thread): def run(self): while not queue.empty(): sleep_times = queue.get() time.sleep(sleep_times) queue.task_done() def main_function(): threads_num = 6 while not stop: put_data_in_queue() for i in xrange(threads_num): myThread = MyThread() myThread.setDaemon(True) myThread.start() queue.join() time.sleep(60) if __name__ == "__main__": original_sigterm = signal.getsignal(signal.SIGTERM) signal.signal(signal.SIGTERM, receive_signal) main_function()
相关推荐
meylovezn 2020-05-30
cenylon 2020-04-29
georgeandgeorge 2020-01-02
数据猿 2019-05-10
liuxiaohua 2019-06-25
jibkfv 2019-06-21
fengling 2019-03-19
zhglinux 2017-01-10
pythonwangjunji 2018-04-27
chouliqingke 2016-11-06
CodeAsWind 2010-02-26
周小董 2018-01-06
AndroidAmelia 2017-11-17
wgPython 2015-06-30
wlpython 2019-04-18
pythoncream 2018-10-24