溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Python如何批量啟動多線程

發(fā)布時間:2021-08-03 10:52:34 來源:億速云 閱讀:316 作者:小新 欄目:開發(fā)技術

這篇文章將為大家詳細講解有關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 = []

  # 傳入多個參數(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)

  # 結束時間
  end = time.time()
  print("完成的時間為:" + str(end - start))

完成同時聽三首歌線程,花費時間 2s:

關于“Python如何批量啟動多線程”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,使各位可以學到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內容。

AI