簡體   English   中英

如何在Python中動態創建多個線程

[英]How to create multiple threads dynamically in Python

我正在創建一個python代碼,該代碼具有一個功能,該功能應運行用戶要求使用線程的次數。 例如:

import time
T = input("Enter the number of times the function should be executed")
L = [1,2,3,4]

def sum(Num):
    for n in Num:
        time.sleep(0.2)
        print("square:",n*n)

基於用戶的T值,我想通過動態創建T'個線程並在單獨的線程中執行sum函數。

如果用戶輸入為4,則需要動態創建4個線程,並使用4個不同的線程執行相同的功能。 請幫我創建4個多線程。謝謝!

這取決於您的需要,您有幾種方法可以做。 這是兩個適合您情況的示例

帶穿線模塊

如果要創建N線程並等待它們結束。 您應該使用threading模塊並導入Thread

from threading import Thread

# Start all threads. 
threads = []
for n in range(T):
    t = Thread(target=sum, args=(L,))
    t.start()
    threads.append(t)

# Wait all threads to finish.
for t in threads:
    t.join()

帶螺紋模塊

否則,以防萬一您不想等待。 我強烈建議您使用thread模塊(自Python3起更_thread _thread)

from _thread import start_new_thread

# Start all threads and ignore exit.
for n in range(T):
    start_new_thread(sum, (L,))

(args,)是一個元組。 這就是L處於括號中的原因。

SUПΣYΛ答案很好地解釋了如何使用多線程,但沒有考慮用戶輸入,用戶輸入根據您的問題定義了線程數。 基於此,您可以嘗試:

import threading, time

def _sum(n):
    time.sleep(0.2)
    print(f"square: {n*n}")

while 1:

    t = input("Enter the number of times the function should be executed:\n").strip()
    try:
        max_threads = int(t)
        for n in range(0, max_threads):
            threading.Thread(target=_sum, args=[n]).start()
    except:
        pass
        print("Please type only digits (0-9)")
        continue

    print(f"Started {max_threads} threads.")

    # wait threads to finish
    while threading.active_count() > 1:
        time.sleep(0.5)

    t = input("Create another batch (y/n)?\n").lower().strip() #
    if t != "y":
        print("Exiting.")
        break

筆記:

  1. 避免創建與內置函數同名的函數,例如sum() ,使用_sum()或類似名稱;
  2. Python是敏感的 ,意味着Def defFor / for ;
  3. 報價單您的字符串'或雙引號" ,而不是 ' ;
  4. 現場演示 -Python 3.6;
  5. 輔助視頻

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM