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
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()
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:
sum()
, use _sum()
or similar name; Def
isn't the same as def
, the same goes For
/ for
; '
or double quotes "
, not '
;
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.