I want to create new Threads while the program is running. I mean, instead of doing like this:
from threading import Thread
# new thread
t1 = Thread(target=someFunc)
t1.join()
I want to do like this:
from threading import Thread
# get input
tname = input('What do you want to call your Thread?') # Let's say 'super'
# The 'super' name here came from input, and 'super' must be a variable.
# The goal is to take the Thread name with input instead of changing the source and create a multiple Threads.
super = Thread(target= someFunc)
super.start()
Is there any way to do this? I tried to do it using a dictionary but I couldn't do it well.
Here's what I try:
import sys
import re
import time
import threading
while True:
# Get input from user
tname = input("What do you want to call your Thread?\n")
# Get thread name using re
def getThreadName(getName=''):
global threadname
threadname = getName
# Create thread giving it a name
try:
threadname = re.search(r'create (.*)', tname)
if threadname:
threadname = list(map(str, threadname.groups()))
threadname = ''.join(threadname)
print("THREAD NAME:", threadname)
except Exception as e:
print(e)
print("Sorry, something went wrong.")
sys.exit()
# Get Thread name using re
getThreadName(tname)
# Target func
def targetfunc():
global threadname
while True:
print(f"I'm the {threadname} Thread!\n")
time.sleep(5)
# Global vars
global threadname
global names
# Create dict
names = dict()
# add new thread and start
names[threadname] = threading.Thread(target = targetfunc)
names[threadname].start()
# Inside the dict
print("INSIDE THE DICT:", names)
In this code, to create Threads, you must use an input like create (threadname)
.
As I said above, The goal is to take the Thread name with input instead of changing the source and create a multiple Threads.
How to achieve this solution? Hope you help.