Python – Run multiple threads at the same time

Run multiple threads at the same time… here is a solution to the problem.

Run multiple threads at the same time

So my goal is to have the do_something() function start its own thread so that do_something() can run in parallel without having to wait for the previous one to finish. The problem is that it doesn’t seem to be multithreaded (meaning one thread finishes before the other starts).

for i in range(len(array_of_letters)):

if i == "a":
        t = threading. Thread(target=do_something())

print "new thread started : %s"%(str(threading.current_thread().ident))     
        t.start()

I also have a current_thread().ident in the do_something() function, but it seems that the identity of the thread started is the same as the main thread running the python script. I don’t think what I’m doing is right.

Solution

This is a common and easy mistake to make.

target=do_something() just executes your function immediately in the main thread and passes None (I guess the return value of your function) as target to the thread’s function, it doesn’t trigger any visible errors; But also do nothing.

You have to pass the actual function instead of the result:

t = threading. Thread(target=do_something)

It would be better

Related Problems and Solutions