Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I run two python loops concurrently?

Tags:

Suppose I have the following in Python

# A loop for i in range(10000):     Do Task A  # B loop for i in range(10000):     Do Task B 

How do I run these loops simultaneously in Python?

like image 215
hiiii Avatar asked Aug 13 '10 06:08

hiiii


People also ask

Can we run two loops simultaneously?

They can't be running simultaneously.

Can you do a double for loop in Python?

In Python, you can simply use a loop inside the loop to get double loops. In Double-loop The “inner loop” will be executed one time for each iteration of the “outer loop”.

How do I run two loops simultaneously in CPP?

Start the first one at the beginning of the word, and the second one at the end, compare the characters at loop indexes, and return false if they are different. If the characters are the same, move to the next iteration by advancing the front index forward and the back index backward.


1 Answers

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.

like image 68
Stefano Palazzo Avatar answered Jan 18 '23 19:01

Stefano Palazzo