I created the following serial code to perform the Odd-even sort ordering, which first sorts the odd / even and odd / even indices.
import time
def oddevenSort(x):
sorted = False
while not sorted:
sorted = True
#ordena indices par/impar
for i in range(0, len(x)-1, 2):
if x[i] > x[i+1]:
x[i], x[i+1] = x[i+1], x[i]
sorted = False
#ordena indices impar/par
for i in range(1, len(x)-1, 2):
if x[i] > x[i+1]:
x[i], x[i+1] = x[i+1], x[i]
sorted = False
print(x)
return x
tic = time.time()
oddevenSort([4,3,2,1,3,6,9,1,2,3,54,76,98,12,333,331,33,1,7,9])
toc = time.time()
print("tempo gasto para processar = " + str(toc-tic)+"s")
Now I need to create a parallel code in python for this same algorithm to be able to calculate the speedup (time gain between executing the serial code VS parallel code).
The first approach I was having was to create a thread for odd / even ordering and another for odd / even sorting, but I can not understand how the behavior of this code will be. In my view this algorithm must execute the whole even / odd part and then in SEQUENCE the odd / even part. So I would have to synchronize thread 1 and thread 2, preventing the code from occurring in parallel.Example thread 1 (even / odd):
for i in range(0, len(x)-1, 2):
if x[i] > x[i+1]:
x[i], x[i+1] = x[i+1], x[i]
sorted = False
Example thread 2 (odd / even):
for i in range(1, len(x)-1, 2):
if x[i] > x[i+1]:
x[i], x[i+1] = x[i+1], x[i]
sorted = False
The second approach would be to parallelize the PAR / TIAR ordering (type 1 thread takes the first half of the numbers and sorts while thread 2 takes the second half and sorts). The same thing for the WIP / PAR part (thread 3 orders half and thread 4 orders the other half).
Example:
Vector complete: (9,8,7,6,5,4,3,2,1,0)
Thread 1 orders: 9,8,7,6,5
Thread 2 orders: 4,3,2,1,0
Expected result thread 1: 5,6,7,8,9
Expected result thread 2: 0,1,2,3,4
Expected result of final ordering: 0,1,2,3,4,5,6,7,8,9
Approach 3? Suggestions? If there is no other way, I'd love to help you implement one of the two suggestions.