0

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.

Shmn
  • 681
  • 1
  • 4
  • 22
Mustafa
  • 59
  • 1
  • 9

1 Answers1

0

I have not implemented the string processing. But if I have understood you correctly this should get you going. Please execute the code and let me know if you have gotten your answer or, anything else is required.

import threading
from time import sleep

def workerFunction(threadName):
    while True:
        print("I'm the {} Thread".format(threadName))
        sleep(5)

def startCreating():
    while True:
        tname = str(input("Enter thread name: "))
        thread = threading.Thread(target=workerFunction, args=(tname,))
        thread.start()

if __name__ == '__main__':
    startCreating()
exilour
  • 516
  • 5
  • 12
  • Input must change the name of variable. Here, you're setting a parameter to function and printing what you wrote. I don't want this. I want to directly change the `thread` variable's name using input. I mean, you wrote `thread.start()` right? I want to change it's name using input. Such as `apple.start()` – Mustafa Aug 24 '20 at 14:37
  • In that case you can try following this answer -> https://stackoverflow.com/a/11553741/5830339 although it works with variables, it doesn't seem to work with class definition. I tried doing it like this `threadDef = "{} = threading.Thread(target=workerFunction, args=({},))".format(threadName, threadName)` and then `exec(threadDef)` . Doesn't seem to work. If you find a solution do post. – exilour Aug 24 '20 at 14:55