5

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!

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

2 Comments

(n) is not a tuple, it's just an int with redundant parentheses. (n,) would be a tuple. Anyway, it seems it should rather be (L,) because sum tries to iterate over the parameter passed to it. Also for n in T does not work, ints are not iterable. You probably meant for n in range(T).
@SUПΣYΛ , the first part of your answer need to be edited also to correct "for n in T:" to "for n in range(T):" and "args=(n)" to "args=(L,)"
0

S U П Σ 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.

3 Comments

That's not really how you wait for threads to finish in Python. Oh, and the other answer does take user input into account (for n in range(T)), it just didn't duplicate the OP's code ;) I like your notes, though, especially the first one.
The other question got updated in the meanwhile. "That's note really how you ...", can be subjective. In this case, when the script starts, there's only one active thread , once we start multi-threading, the threading.active_count() increases above 1 and when no "extra threads" are active, it returns to 1. Thank you for the remarks on the notes.
Sleep is terrible, never use it, except in tests/mocks, to simulate delays. Use thread's join method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.