Following the trend, I created a thread-safe function that returns sort results. Would you like to make something like multiprocessing or joblib?
from threading import Thread, Lock
from time import sleep
def sleep_sort(values):
sorted_values = []
lock = Lock()
def worker(value):
sleep(value)
with lock: sorted_values.append(value)
threads = [Thread(target=worker, args=(value,)) for value in values]
for thread in threads: thread.start()
for thread in threads: thread.join()
return sorted_values
array = [5, 3, 6, 3, 6, 3, 1, 4, 7]
print(sleep_sort(array))
Execution result (this script takes 7 seconds to execute)
[1, 3, 3, 3, 4, 5, 6, 6, 7]
reference: 2012/03/16 Let's write sleep sort generically in Ruby. 2013/05/15 Explanation of sleep sort 2013/10/24 Training sleepsort 2015/06/09 Rust and Sleep sort 2015/06/25 I wrote sleep sort in C # 2015/10/21 I implemented sleep sort in parallel processing of C ++ 2016/11/15 Multi-thread comparison with Sleep Sort (js / TS / VB / C # / C ++ / D / Go / HSP (mist)) 2017/04/24 [[Neta] Sleep Sort with Swift]([Neta] Sleep Sort with Swift) 2017/04/24 [Neta] Sleep Sort with JavaScript 2017/04/26 [Neta] Sleep Sort in Java 2017/04/26 [Neta] Sleep Sort in Python 2017/04/26 sleep sort
Recommended Posts