0

I am new to python. for loop iterates element one by one. I want to know how to execute all the elements in the for loop at the same time. Here is my sample code:

import time
def mt():
    for i in range(5):
        print (i)
        time.sleep(1)
mt()

It prints the element one by one from for loop and wait 1 sec for next element. I want to know how to use multi-threading in for loop to print all the elements at the same time without waiting for next element

2 Answers 2

4

You can use the multiprocessing module as shown in the example below:

import time
from multiprocessing import Pool

def main():
    p = Pool(processes=5)
    result = p.map(some_func, range(5))

def some_func(i):
    print(i)
    time.sleep(1)

if __name__ == '__main__':
    main()
Sign up to request clarification or add additional context in comments.

Comments

1

You can also try import threading Concept.

import threading
import time

def mt(i):
    print (i)
    time.sleep(1)

def main():
    for i in range(5):
        threadProcess = threading.Thread(name='simplethread', target=mt, args=[i])
        threadProcess.daemon = True
        threadProcess.start()
main()

1 Comment

Thanks for the answer. It also worked for my project

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.