python多线程:控制线程数量 https://www.cnblogs.com/hanmk/p/12990017.html
使用线程池 https://zhuanlan.zhihu.com/p/627853937
1.自定义线程池
1 import threading 2 import Queue 3 import time 4 5 queue = Queue.Queue() 6 7 8 def put_data_in_queue(): 9 for i in xrange(10): 10 queue.put(i) 11 12 13 class MyThread(threading.Thread): 14 def run(self): 15 while not queue.empty(): 16 sleep_times = queue.get() 17 time.sleep(sleep_times) 18 queue.task_done() 19 20 21 def main_function(): 22 threads_num = 6 23 while True: 24 put_data_in_queue() 25 for i in xrange(threads_num): 26 myThread = MyThread() 27 myThread.setDaemon(True) 28 myThread.start() 29 queue.join() 30 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()