How do I run two python loops concurrently?

If you want concurrency, here’s a very simple example:

from multiprocessing import Process

def loop_a():
    while 1:
        print("a")

def loop_b():
    while 1:
        print("b")

if __name__ == '__main__':
    Process(target=loop_a).start()
    Process(target=loop_b).start()

This is just the most basic example I could think of. Be sure to read http://docs.python.org/library/multiprocessing.html to understand what’s happening.

If you want to send data back to the program, I’d recommend using a Queue (which in my experience is easiest to use).

You can use a thread instead if you don’t mind the global interpreter lock. Processes are more expensive to instantiate but they offer true concurrency.

Leave a Comment