@@ -49,31 +49,34 @@ def oe_process[T: Comparable](
4949 # we perform n swaps since after n swaps we know we are sorted
5050 # we *could* stop early if we are sorted already, but it takes as long to
5151 # find out we are sorted as it does to sort the list with this algorithm
52- for i in range (10 ):
53- if (i + position ) % 2 == 0 and r_send is not None :
54- # send your value to your right neighbor
55- with process_lock :
56- r_send [1 ].send (value )
57-
58- # receive your right neighbor's value
59- with process_lock :
60- temp = rr_cv [0 ].recv ()
61-
62- # take the lower value since you are on the left
63- value = min (value , temp )
64- elif (i + position ) % 2 != 0 and l_send is not None :
65- # send your value to your left neighbor
66- with process_lock :
67- l_send [1 ].send (value )
68-
69- # receive your left neighbor's value
70- with process_lock :
71- temp = lr_cv [0 ].recv ()
72-
73- # take the higher value since you are on the right
74- value = max (value , temp )
75- # after all swaps are performed, send the values back to main
76- result_pipe [1 ].send (value )
52+ try :
53+ for i in range (10 ):
54+ if (i + position ) % 2 == 0 and r_send is not None :
55+ # send your value to your right neighbor
56+ with process_lock :
57+ r_send [1 ].send (value )
58+
59+ # receive your right neighbor's value
60+ with process_lock :
61+ temp = rr_cv [0 ].recv ()
62+
63+ # take the lower value since you are on the left
64+ value = min (value , temp )
65+ elif (i + position ) % 2 != 0 and l_send is not None :
66+ # send your value to your left neighbor
67+ with process_lock :
68+ l_send [1 ].send (value )
69+
70+ # receive your left neighbor's value
71+ with process_lock :
72+ temp = lr_cv [0 ].recv ()
73+
74+ # take the higher value since you are on the right
75+ value = max (value , temp )
76+ # after all swaps are performed, send the value back to main
77+ result_pipe [1 ].send ((False , value ))
78+ except Exception as e : # noqa: BLE001
79+ result_pipe [1 ].send ((True , e ))
7780
7881
7982def odd_even_transposition [T : Comparable ](arr : list [T ]) -> list [T ]:
@@ -105,6 +108,9 @@ def odd_even_transposition[T: Comparable](arr: list[T]) -> list[T]:
105108 >>> odd_even_transposition(unsorted_list) == sorted(unsorted_list)
106109 True
107110 """
111+ if not arr :
112+ return arr
113+
108114 # spawn method is considered safer than fork
109115 multiprocessing_context = mp .get_context ("spawn" )
110116
@@ -179,7 +185,12 @@ def odd_even_transposition[T: Comparable](arr: list[T]) -> list[T]:
179185
180186 # wait for the processes to end and write their values to the list
181187 for p in range (len (result_pipe )):
182- arr [p ] = result_pipe [p ][0 ].recv ()
188+ is_error , result = result_pipe [p ][0 ].recv ()
189+ if is_error :
190+ for proc in process_array_ :
191+ proc .terminate ()
192+ raise result
193+ arr [p ] = result
183194 process_array_ [p ].join ()
184195 return arr
185196
0 commit comments