python自定义线程池控制线程数量的示例
1.自定义线程池
importthreading importQueue importtime queue=Queue.Queue() defput_data_in_queue(): foriinxrange(10): queue.put(i) classMyThread(threading.Thread): defrun(self): whilenotqueue.empty(): sleep_times=queue.get() time.sleep(sleep_times) queue.task_done() defmain_function(): threads_num=6 whileTrue: put_data_in_queue() foriinxrange(threads_num): myThread=MyThread() myThread.setDaemon(True) myThread.start() queue.join() time.sleep(60)
2.多线程与signal信号的监控结合
importthreading importQueue importtime importsignal queue=Queue.Queue() stop=False defreceive_signal(signum,stack): signal.signal(signal.SIGTERM,original_sigterm) globalstop stop=True defput_data_in_queue(): foriinxrange(10): queue.put(i) classMyThread(threading.Thread): defrun(self): whilenotqueue.empty(): sleep_times=queue.get() time.sleep(sleep_times) queue.task_done() defmain_function(): threads_num=6 whilenotstop: put_data_in_queue() foriinxrange(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()
以上这篇python自定义线程池控制线程数量的示例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。