How to parallelize 2 loops in python
<p>I need to make each iteration in different thread (for each of these 2 loops). </p>

<pre><code>var = 5
a = -7
b = 7
for i in range(var):
    for j in range(a, b):
        print(i, "   ", j)
</code></pre>

<p>How can I make it?</p>

<p>UPD:</p>

<pre><code>var = 5
a = -7
b = 7
max = 0
for i in range(var):
    for j in range(a, b):
        print(i, "   ", j)
        if i+j&gt;max:
            max=i+j
print(max)
</code></pre>

<p>You can not run these two loops in different threads because the second loop have dependency to the data which is produced in first loop.</p>

<p>One way is to run each iteration of first loop in a different thread like this:</p>

<pre><code>from threading import Thread
var = 5
a = -7
b = 7

def inner_loop(i):
    for j in range(a, b):
        print(i, "   ", j)

for i in range(var):
    Thread(target=inner_loop, args=[i]).start()
</code></pre>

<p>Another way is producer consumer pattern. First loop generate <code>i</code> value and add it to a queue and second loop read values from queue and generate <code>j</code> and print <code>i</code> and <code>j</code> like this:</p>

<pre><code>from threading import Thread

var = 5
a = -7
b = 7

queue = []
finished = False

def inner_loop():
    while not finished or len(queue) &gt; 0:
        if len(queue) == 0:
            continue
        i = queue.pop()
        for j in range(a, b):
            print(i, "   ", j)

def first_loop():
    for i in range(var):
        queue.append(i)
    finished = True

Thread(target=inner_loop).start()
Thread(target=first_loop).start()
</code></pre>

python multithreading