How do I run two python loops concurrently?


You will need to use a multiprocessing library. You will need to spawn a new process and provide the code to it as an argument. For example,

from multiprocessing import Process

def loop_a():
   for i in range(5):
      print("a")

def loop_b():
   for i in range(5):
      print("b")

Process(target=loop_a).start()
Process(target=loop_b).start()

This might process different outputs at different times. This is because we don't know which print will be executed when.

Lakshmi Srinivas
Lakshmi Srinivas

Programmer / Analyst / Technician

Updated on: 17-Jun-2020

532 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements