Python自訂進程池實例分析【生產者、消費者模型問題】
本文實例分析了Python自訂進程池。分享給大家供大家參考,具體如下:
程式碼說明一切:
##encoding=utf-8 #author: walker #date: 2014-05-21 #function: 自定义进程池遍历目录下文件 from multiprocessing import Process, Queue, Lock import time, os #消费者 class Consumer(Process): def __init__(self, queue, ioLock): super(Consumer, self).__init__() self.queue = queue self.ioLock = ioLock def run(self): while True: task = self.queue.get() #队列中无任务时,会阻塞进程 if isinstance(task, str) and task == 'quit': break; time.sleep(1) #假定任务处理需要1秒钟 self.ioLock.acquire() print( str(os.getpid()) + ' ' + task) self.ioLock.release() self.ioLock.acquire() print 'Bye-bye' self.ioLock.release() #生产者 def Producer(): queue = Queue() #这个队列是进程/线程安全的 ioLock = Lock() subNum = 4 #子进程数量 workers = build_worker_pool(queue, ioLock, subNum) start_time = time.time() for parent, dirnames, filenames in os.walk(r'D:\test'): for filename in filenames: queue.put(filename) ioLock.acquire() print('qsize:' + str(queue.qsize())) ioLock.release() while queue.qsize() > subNum * 10: #控制队列中任务数量 time.sleep(1) for worker in workers: queue.put('quit') for worker in workers: worker.join() ioLock.acquire() print('Done! Time taken: {}'.format(time.time() - start_time)) ioLock.release() #创建进程池 def build_worker_pool(queue, ioLock, size): workers = [] for _ in range(size): worker = Consumer(queue, ioLock) worker.start() workers.append(worker) return workers if __name__ == '__main__': Producer()
self.ioLock.acquire() ... self.ioLock.release()
with self.ioLock: ...
#encoding=utf-8 #author: walker #date: 2016-01-06 #function: 一个多进程的好玩例子 import os, sys, time from multiprocessing import Pool cur_dir_fullpath = os.path.dirname(os.path.abspath(__file__)) g_List = ['a'] #修改全局变量g_List def ModifyDict_1(): global g_List g_List.append('b') #修改全局变量g_List def ModifyDict_2(): global g_List g_List.append('c') #处理一个 def ProcOne(num): print('ProcOne ' + str(num) + ', g_List:' + repr(g_List)) #处理所有 def ProcAll(): pool = Pool(processes = 4) for i in range(1, 20): #ProcOne(i) #pool.apply(ProcOne, (i,)) pool.apply_async(ProcOne, (i,)) pool.close() pool.join() ModifyDict_1() #修改全局变量g_List if __name__ == '__main__': ModifyDict_2() #修改全局变量g_List print('In main g_List :' + repr(g_List)) ProcAll()
λ python3 demo.py In main g_List :['a', 'b', 'c'] ProcOne 1, g_List:['a', 'b'] ProcOne 2, g_List:['a', 'b'] ProcOne 3, g_List:['a', 'b'] ProcOne 4, g_List:['a', 'b'] ProcOne 5, g_List:['a', 'b'] ProcOne 6, g_List:['a', 'b'] ProcOne 7, g_List:['a', 'b'] ProcOne 8, g_List:['a', 'b'] ProcOne 9, g_List:['a', 'b'] ProcOne 10, g_List:['a', 'b'] ProcOne 11, g_List:['a', 'b'] ProcOne 12, g_List:['a', 'b'] ProcOne 13, g_List:['a', 'b'] ProcOne 14, g_List:['a', 'b'] ProcOne 15, g_List:['a', 'b'] ProcOne 16, g_List:['a', 'b'] ProcOne 17, g_List:['a', 'b'] ProcOne 18, g_List:['a', 'b'] ProcOne 19, g_List:['a', 'b']
In main g_List :['a', 'b', 'c'] ProcOne 1, g_List:['a', 'b', 'c'] ProcOne 2, g_List:['a', 'b', 'c'] ProcOne 3, g_List:['a', 'b', 'c'] ProcOne 5, g_List:['a', 'b', 'c'] ProcOne 4, g_List:['a', 'b', 'c'] ProcOne 8, g_List:['a', 'b', 'c'] ProcOne 9, g_List:['a', 'b', 'c'] ProcOne 7, g_List:['a', 'b', 'c'] ProcOne 11, g_List:['a', 'b', 'c'] ProcOne 6, g_List:['a', 'b', 'c'] ProcOne 12, g_List:['a', 'b', 'c'] ProcOne 13, g_List:['a', 'b', 'c'] ProcOne 10, g_List:['a', 'b', 'c'] ProcOne 14, g_List:['a', 'b', 'c'] ProcOne 15, g_List:['a', 'b', 'c'] ProcOne 16, g_List:['a', 'b', 'c'] ProcOne 17, g_List:['a', 'b', 'c'] ProcOne 18, g_List:['a', 'b', 'c'] ProcOne 19, g_List:['a', 'b', 'c']

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

Python适合数据科学、Web开发和自动化任务,而C 适用于系统编程、游戏开发和嵌入式系统。Python以简洁和强大的生态系统著称,C 则以高性能和底层控制能力闻名。

Python在遊戲和GUI開發中表現出色。 1)遊戲開發使用Pygame,提供繪圖、音頻等功能,適合創建2D遊戲。 2)GUI開發可選擇Tkinter或PyQt,Tkinter簡單易用,PyQt功能豐富,適合專業開發。

Python更易學且易用,C 則更強大但複雜。 1.Python語法簡潔,適合初學者,動態類型和自動內存管理使其易用,但可能導致運行時錯誤。 2.C 提供低級控制和高級特性,適合高性能應用,但學習門檻高,需手動管理內存和類型安全。

要在有限的時間內最大化學習Python的效率,可以使用Python的datetime、time和schedule模塊。 1.datetime模塊用於記錄和規劃學習時間。 2.time模塊幫助設置學習和休息時間。 3.schedule模塊自動化安排每週學習任務。

Python在開發效率上優於C ,但C 在執行性能上更高。 1.Python的簡潔語法和豐富庫提高開發效率。 2.C 的編譯型特性和硬件控制提升執行性能。選擇時需根據項目需求權衡開發速度與執行效率。

Python在自動化、腳本編寫和任務管理中表現出色。 1)自動化:通過標準庫如os、shutil實現文件備份。 2)腳本編寫:使用psutil庫監控系統資源。 3)任務管理:利用schedule庫調度任務。 Python的易用性和豐富庫支持使其在這些領域中成為首選工具。

pythonlistsarepartofthestAndArdLibrary,herilearRaysarenot.listsarebuilt-In,多功能,和Rused ForStoringCollections,而EasaraySaraySaraySaraysaraySaraySaraysaraySaraysarrayModuleandleandleandlesscommonlyusedDduetolimitedFunctionalityFunctionalityFunctionality。

每天學習Python兩個小時是否足夠?這取決於你的目標和學習方法。 1)制定清晰的學習計劃,2)選擇合適的學習資源和方法,3)動手實踐和復習鞏固,可以在這段時間內逐步掌握Python的基本知識和高級功能。
