Python批量啟動多線程代碼實例
更新時間:2020年02月18日 10:15:47 作者:TTyb
這篇文章主要介紹了python批量啟動多線程代碼實例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
這篇文章主要介紹了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) # 假設(shè)每一首歌曲的時間是2秒 time.sleep(2) if __name__ == '__main__': # 設(shè)定我要聽的歌為 musics = ["music1", "music2", "music3"] test = "122678" # 開始時間 start = time.time() threadpool = [] # 傳入多個參數(shù) for music in musics: # 傳入單個參數(shù)請寫成 # 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) # 結(jié)束時間 end = time.time() print("完成的時間為:" + str(end - start))
完成同時聽三首歌線程,花費時間 2s:
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Python基于ssh遠程連接Mysql數(shù)據(jù)庫操作
這篇文章主要為大家介紹了Python基于ssh遠程連接Mysql數(shù)據(jù)庫操作示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-06-06Python數(shù)據(jù)處理之savetxt()和loadtxt()使用詳解
這篇文章主要介紹了Python數(shù)據(jù)處理之savetxt()和loadtxt()使用詳解,NumPy提供了多種存取數(shù)組內(nèi)容的文件操作函數(shù),保存數(shù)組數(shù)據(jù)的文件可以是二進制格式或者文本格式,今天我們來看看savetxt()和loadtxt()的用法,需要的朋友可以參考下2023-08-08Pandas出現(xiàn)KeyError的問題解決及分析
本文主要介紹了Pandas出現(xiàn)KeyError的問題解決及分析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-01-01python使用ctypes調(diào)用dll遇到的坑解決記錄
這篇文章主要為大家介紹了python使用ctypes調(diào)用dll遇到的坑解決記錄,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-12-12Python常用字符串替換函數(shù)strip、replace及sub用法示例
這篇文章主要介紹了Python常用字符串替換函數(shù)strip、replace及sub用法,結(jié)合實例形式分析了Python針對字符串替換的常用函數(shù)strip、replace及sub功能及簡單使用技巧,需要的朋友可以參考下2018-05-05