[FIXED] Run the same for loop's different iterations at the same time

Issue

There was another question like this but the answer wasn't clear

Trying to make a for loop faster by running each iteration at the same time

for i in something:
   print(i) # I would want this code to be executed all at the same time


Solution

still requires a for loop, but Im assuming the code inside each loop is lengthy and takes time, so heres how you could start a thread for each loop then wait till all threads are finished before continuing

import threading

def myfunc(*args):
    #do something
    return

threads=[]

for n,i in enumerate(something):
     threads.append(threading.Thread(target = myfunc, args = (i,))) #args needs to be a tuple, even with only 1 element
     threads[n].start()

for thread in threads:
    thread.join()


Answered By - Christian Trujillo
Answer Checked By - Katrina (Python.Easybugfix Volunteer)

Related Posts

Post a Comment