python多進程使用及線程池的使用方法代碼詳解
多進程:主要運行multiprocessing模塊
import os,time
import sys
from multiprocessing import Process
class MyProcess(Process):
"""docstring for MyProcess"""
def __init__(self, arg, callback):
super(MyProcess, self).__init__()
self.arg = arg
self.callback = callback
def run(self):
self.callback(self.arg)
def test(arg):
print("子進程{}開始>>> pid={}".format(arg,os.getpid()))
for i in range(1,5):
sys.stdout.write("子進程{}運行中{}\r".format(arg,i))
sys.stdout.flush()
time.sleep(1)
def main():
print("主進程開始>>> pid={}".format(os.getpid()))
myp=MyProcess(1,test)
myp.start()
myp2=MyProcess(2,test)
myp2.start()
myp.join()
myp2.join()
print("主進程終止")
if __name__ == '__main__':
main()
線程池:主要運用了未來模塊!下面例子,第一個是正常,第二第線程池,第三個用運行了2個線程池,會排隊
from concurrent.futures import ThreadPoolExecutor
import time
def sayhello(a):
print("hello: "+a)
time.sleep(2)
def main():
seed=["a","b","c"]
start1=time.time()
for each in seed:
sayhello(each)
end1=time.time()
print("time1: "+str(end1-start1))
start2=time.time()
with ThreadPoolExecutor(3) as executor:
for each in seed:
executor.submit(sayhello,each)
end2=time.time()
print("time2: "+str(end2-start2))
start3=time.time()
with ThreadPoolExecutor(2) as executor1:
executor1.map(sayhello,seed)
end3=time.time()
print("time3: "+str(end3-start3))
if __name__ == '__main__':
main()
總結(jié)
以上所述是小編給大家介紹的python多進程使用及線程池的使用方法代碼詳解,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關(guān)文章
Python使用logging結(jié)合decorator模式實現(xiàn)優(yōu)化日志輸出的方法
這篇文章主要介紹了Python使用logging結(jié)合decorator模式實現(xiàn)優(yōu)化日志輸出的方法,實例分析了Python使用logging模塊操作日志的相關(guān)技巧,需要的朋友可以參考下2016-04-04
Django 響應數(shù)據(jù)response的返回源碼詳解
這篇文章主要介紹了Django 響應數(shù)據(jù)response的返回源碼詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2019-08-08
python中常用檢測字符串相關(guān)函數(shù)匯總
這篇文章主要介紹了python中常用檢測字符串相關(guān)函數(shù),實例匯總了Python針對字符串數(shù)字、字母、大小寫等常用檢測函數(shù),非常具有實用價值,需要的朋友可以參考下2015-04-04
python中可以發(fā)生異常自動重試庫retrying
這篇文章主要介紹了python中可以發(fā)生異常自動重試庫retrying,retrying是一個極簡的使用Python編寫的庫,主題更多相關(guān)內(nèi)容需要的朋友可以參考一下2022-06-06
在PyTorch中實現(xiàn)可解釋的神經(jīng)網(wǎng)絡模型的方法詳解
這篇文章主要為大家介紹在PyTorch如何中實現(xiàn)可解釋的神經(jīng)網(wǎng)絡模型,并為您提供使用簡單的 PyTorch 接口實現(xiàn)最先進的基于概念的模型的工具,需要的朋友可以參考下2023-06-06
calendar在python3時間中常用函數(shù)舉例詳解
這篇文章主要介紹了calendar在python3時間中常用函數(shù)的相關(guān)文章,對此知識點有興趣的朋友們可以學習下。2020-11-11
pycharm遠程連接服務器并配置python interpreter的方法
這篇文章主要介紹了pycharm遠程連接服務器并配置python interpreter的方法,本文通過圖文并茂的形式給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-12-12
Python利用Selenium進行網(wǎng)頁自動化與動態(tài)內(nèi)容抓取操作
Selenium是一個自動化測試工具,它允許開發(fā)者模擬用戶的瀏覽器行為,執(zhí)行各種交互操作,下面就跟隨小編一起了解下如何使用Python和Selenium進行網(wǎng)頁自動化與動態(tài)內(nèi)容抓取吧2025-03-03

