Beras Mark
Beras Mark

Reputation: 53

How to parallelize 2 loops in python

I need to make each iteration in different thread (for each of these 2 loops).

var = 5
a = -7
b = 7
for i in range(var):
    for j in range(a, b):
        print(i, "   ", j)

How can I make it?

UPD:

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>max:
            max=i+j
print(max)

Upvotes: 1

Views: 82

Answers (2)

owobeid
owobeid

Reputation: 183

If you want true multi-threading (which the 'threading' library doesn't do!) use the 'multiprocessing' library. The introduction section in the docs has a good example.

Upvotes: 1

Bardia Heydari
Bardia Heydari

Reputation: 774

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.

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

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()

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

from threading import Thread

var = 5
a = -7
b = 7

queue = []
finished = False

def inner_loop():
    while not finished or len(queue) > 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()

Upvotes: 1

Related Questions