Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Threading - Make threads start without waiting for previous thread to finish

I want all of my threads to start at the same time, but in my code, it waits for the previous thread to finish it's process before starting a new one. I want all of the threads to start in parallel.

My Code:

class Main(object):

    start = True
    config = True
    givenName = True

    def obscure(self, i):
        i = i

        while self.start:
            Config.userInfo(i)
            break
        while self.config:
            Config.open()
            break
        while self.givenName:
            Browser.openSession()
            break

Main = Main()

while __name__=='__main__':
    Config.userInfo()
    Config.open()
    for i in range(len(Config.names)):
        Task = Thread(target=Main.obscure(i))
        Task.start()
    break
like image 793
Michael Avatar asked Jun 13 '26 14:06

Michael


1 Answers

This line is the main problem:

Task = Thread(target=Main.obscure(i))

target is passed the result of calling Main.obscure(i), not the function to be run in the thread. You are currently running the function in the main thread then passing, essentially, target=None.

You want:

Task = Thread(target=Main.obscure, args=(i,))

Then, Thread will arrange to call Main.obscure with the listed arguments inside the thread.

Also, Main = Main() overwrites the class Main declaration with an instance of Main...but you'll never be able to make another instance since you've lost the reference to the class. Use another name, such as main = Main().

like image 199
Mark Tolonen Avatar answered Jun 16 '26 02:06

Mark Tolonen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!