7
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【ネタ】Pythonでスレッドセーフな Sleep Sort関数 (threading編)

Last updated at Posted at 2017-04-26

流行りに乗って、ソート結果を返すスレッドセーフな関数を作ってみました。
multiprocessing編とか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))
実行結果(このスクリプトでは実行に7秒かかる)
[1, 3, 3, 3, 4, 5, 6, 6, 7]

参考:
2012/03/16 スリープソートをRubyで汎用的に書いてみる。
2013/05/15 sleep sort の解説
2013/10/24 手習いsleepsort
2015/06/09 RustとSleep sort
2015/06/25 C#でスリープソート書きました
2015/10/21 C++の並列処理でsleep sortを実装してみた
2016/11/15 Sleep Sortでマルチスレッド比較(js/TS/VB/C#/C++/D/Go/HSP(mist))
2017/04/24 [【ネタ】Swift で Sleep Sort](【ネタ】Swift で Sleep Sort)
2017/04/24 【ネタ】JavaScriptでSleep Sort
2017/04/26 【ネタ】Java で Sleep Sort
2017/04/26 【ネタ】PythonでSleep Sort
2017/04/26 sleep sort

7
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?