Python批量啟動多執行緒程式碼例項
阿新 • • 發佈:2020-02-18
這篇文章主要介紹了python批量啟動多執行緒程式碼例項,文中通過示例程式碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
建立一個執行緒池,並將某個執行緒放入進去
threadpool = [] th = threading.Thread(target=func_name,args=func_args) threadpool.append(th)
批量加入執行緒
for i in range(10): th = threading.Thread(target=func_name,args=func_args) threadpool.append(th)
批量開始執行緒
for th in threadpool: th.start() for th in threadpool: threading.Thread.join(th)
例項如下:
#!/usr/bin/python3.4 # -*- coding: utf-8 -*- import time import threading def matter1(music,test): print(test,music) # 假設每一首歌曲的時間是2秒 time.sleep(2) if __name__ == '__main__': # 設定我要聽的歌為 musics = ["music1","music2","music3"] test = "122678" # 開始時間 start = time.time() threadpool = [] # 傳入多個引數 for music in musics: # 傳入單個引數請寫成 # args=(arg1,) th = threading.Thread(target=matter1,args=(music,test)) threadpool.append(th) for th in threadpool: th.start() for th in threadpool: threading.Thread.join(th) # 結束時間 end = time.time() print("完成的時間為:" + str(end - start))
完成同時聽三首歌執行緒,花費時間 2s:
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。