[Python] I am stuck in this python multithreading program

Discussão em 'Python' iniciado por Stack, Abril 19, 2025.

  1. Stack

    Stack Membro Participativo

    Objective:

    To work with Multithreading

    Problem Description:

    In a Proof Of Concept demo, a program must spawn "n" number of threads from the main thread. Get the number of threads that need to be spawned and spawn the threads from the main.

    Ex: If the number of threads that need to be spawned is 2 then the output must be generated from the thread asThread1 is running Thread2 is running where Thread1 and Thread2 are the names assigned to each thread being spawnedÂ

    Note:

    1. The user-defined thread class(MultithreadingDemo) must extend the Thread class. This class should contain a variable name with default as None. An appropriate getter setter method is given already.

    Â 2. The run() method of the MultithreadingDemo class should be executed when the thread is started. In this method, the current thread's name should be obtained using the appropriate method of the threading module, and set the thread's name using the corresponding setter method. Then the thread's name is then printed.

    3. The class Multithread must implement the main method from which the threads have to be started.

    Sample input and output:

    Enter the number of threads to spawn: 8

    Thread-1 is running

    Thread-2 is running

    Thread-3 is running

    Thread-4 is running

    Thread-5 is running

    Thread-6 is running

    Thread-7 is running

    Thread-8 is running

    Code that i tried :

    import threading

    class MultithreadingDemo(threading.Thread):
    def __init__(self):
    super().__init__()
    self.__name = None

    def get_name(self):
    return self.__name

    def set_name(self,name):
    self.__name = name

    def run(self):
    curr_name = threading.current_thread().name
    self.set_name(curr_name)
    print(f"\n{self.get_name()} is running")

    class Multithread:
    @staticmethod
    def main():
    num = int(input("Enter the number of threads to spawn: "))
    threads = []

    for i in range(num):
    t = MultithreadingDemo()
    t.start()
    threads.append(t)

    for t in threads:
    t.join()

    if __name__=="__main__":
    Multithread.main()



    Result : Proposed grade: 70.0 / 100 Result Description Fail 1 :: The 'run()' method for setting the thread name is NOT implemented properly.. Check whether the thread class and its functions are implemented as per the requirement.

    Continue reading...

Compartilhe esta Página