您好,登錄后才能下訂單哦!
這期內容當中小編將會給大家帶來有關python中怎么控制進程或線程的個數,文章內容豐富且以專業的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。
如下例demo所示, 創建了一個大小是4的進程池,然后創建5個進程,并啟動
from multiprocessing import Pool import os, time, random def long_time_task(name): print('Run task %s (%s)...' % (name, os.getpid())) start = time.time() time.sleep(random.random() * 3) end = time.time() print('Task %s runs %0.2f seconds.' % (name, (end - start))) if __name__ == '__main__': print('Parent process %s.' % os.getpid()) p = Pool(4) for i in range(5): p.apply_async(long_time_task, args=(i,)) print('Waiting for all subprocesses done...') p.close() p.join() print('All subprocesses done.')
運行結果如下,可以看到第5個進程會等池子里的進程完成一個后才會被啟動
Run task 0 (32952)... Run task 1 (32951)... Run task 2 (32953)... Run task 3 (32954)... Task 2 runs 0.68 seconds. Run task 4 (32953)... Task 1 runs 1.41 seconds. Task 0 runs 1.44 seconds. Task 4 runs 2.15 seconds. Task 3 runs 2.98 seconds. All subprocesses done.
queue 模塊即隊列,特別適合處理信息在多個線程間安全交換的多線程程序中。 下面的demo展示了如何通過queue來限制線程的并發個數
import threading import queue import time import random import os maxThreads = 4 class Store(threading.Thread): def __init__(self, q): threading.Thread.__init__(self) self.queue = q # self.store = store def run(self): try: print('Run task (%s)...' % (os.getpid())) start = time.time() time.sleep(random.random() * 3) end = time.time() t = threading.currentThread() # 線程ID print('Thread id : %d' % t.ident) print('Thread name : %s' % t.getName()) print('Task runs %0.2f seconds.' % (end - start)) except Exception as e: print(e) finally: self.queue.get() self.queue.task_done() def main(): q = queue.Queue(maxThreads) for s in range(6): q.put(s) t = Store(q) t.start() q.join() print('over') if __name__ == '__main__': main()
運行結果如下:
Run task (33259)... Run task (33259)... Run task (33259)... Run task (33259)... Thread id : 123145444999168 Thread name : Thread-13 Task runs 0.04 seconds. Run task (33259)... Thread id : 123145394630656 Thread name : Thread-10 Task runs 1.02 seconds. Run task (33259)... Thread id : 123145428209664 Thread name : Thread-12 Task runs 1.20 seconds. Thread id : 123145394630656 Thread name : Thread-17 Task runs 0.68 seconds. Thread id : 123145444999168 Thread name : Thread-14 Task runs 1.79 seconds. Thread id : 123145411420160 Thread name : Thread-11 Task runs 2.96 seconds. over
上述就是小編為大家分享的python中怎么控制進程或線程的個數了,如果剛好有類似的疑惑,不妨參照上述分析進行理解。如果想知道更多相關知識,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。