您好,登錄后才能下訂單哦!
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()
以上這篇python自定義線程池控制線程數量的示例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。