简体   繁体   中英

How to create multiple threads dynamically in Python

I am creating a python code that have a function which should be run for number of times user asks using threads. Eg:

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)

Based on the value of T from user, I want tho create T' number of threads dynamically and execute the sum function in separate threads.

If user gives input as 4 then I need to create 4 threads dynamically and execute the same function with 4 different threads. Please help me out to create 4 multiple threads.Thanks!

It depends on your needs, you have several ways to do. Here is two examples suitable for your case

With threading module

If you want to create N threads and wait for them to end. You should use the threading module and import 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()

With thread module

Otherwise, in case you do not want to wait. I strongly advise you to use the thread module (renamed _thread since Python3) .

from _thread import start_new_thread

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

(args,) are a tuple. It's why L is in parantheses.

SU П Σ Y Λ answer explains well how to use multi-threading, but didn't take into account user input, which, according to your question, defines the number of threads. Based on that, you can try:

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

Notes:

  1. Avoid creating functions with the same name as builtin functions, like sum() , use _sum() or similar name;
  2. Python is caSe SenSiTive , meaning that Def isn't the same as def , the same goes For / for ;
  3. Quote your strings with single ' or double quotes " , not ' ;
  4. Live Demo - Python 3.6;
  5. Asciinema video .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM