LoginSignup
1
0

More than 5 years have passed since last update.

【ネタ】SmalltalkでスレッドセーフなSleepSort

Last updated at Posted at 2017-05-29

流行りに乗って(^^; 、Smalltalk でスレッドセーフなSleepSortを書いてみました。

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

処理系は Pharo を使用しました。

| N queue result |
N := 1000.
queue := SharedQueue new.
(1 to: N) asArray shuffled do: [:x |
   [(Delay forMilliseconds: x * 5) wait. queue nextPut: x] fork
].
^[result := (queue next: N) asArray] timeToRun -> result isSorted
=> 0:00:00:05.002->true

処理は簡単で、1 から N := 1000 までの整数の配列((1 to: N) asArray)をランダムに並び替え(shuffled)てから、それぞれの整数 x について x * 5 ミリ秒待ってから((Delay forMilliseconds: x * 5) wait)、キューに x を追加する作業(queue nextPut: x)を別スレッドで動かします([...] fork)。

その後、メインスレッドでキューに N 個要素がたまるのを待って結果とします(result := (queue next: N) asArray)。

念のため、そのときにかかった時間([...] timeToRun)が、N * 5 ミリ秒、つまり 5 秒を大きく越えていないことと結果がソート済み(result isSorted)であることを確認しています。

1
0
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
1
0