多线程合并排序

时间:2016-04-15 06:52:46

标签: ruby multithreading algorithm sorting concurrency

如何在Ruby中实现实现?特别是,如何将生成的线程的结果返回到主线程?

def merge_sort(array)
  return array if base_case?(array)

  first_half, second_half = split_into_halves(array)

  # spawn recursive calls
  first_spawn = Thread.new {
    sorted_first_half  = merge_sort(first_half)
  }

  second_spawn = Thread.new {
    sorted_second_half = merge_sort(second_half)
  }

  # sync
  first_spawn.join
  second_spawn.join

  merge(sorted_first_half, sorted_second_half)
end

1 个答案:

答案 0 :(得分:1)

这是我在Ruby中并行merge sort的实现。在Ruby 2.3.x中测试过。

module ParallelMergeSort

  def merge_sorted
    return self if size <= 1

    split = size / 2

    # Divide into sub-threads
    part_a, part_b = [
        Thread.new { self.slice(0, split).merge_sorted },
        Thread.new { self.slice(split, self.size - split).merge_sorted }
    ].map(&:join).map(&:value)

    # Conquer and return
    array = self.class.new
    off_a, off_b = [0, 0]

    while off_a < part_a.size && off_b < part_b.size
      a, b = part_a[off_a], part_b[off_b]

      if a <= b
        array << a
        off_a += 1
      else
        array << b
        off_b += 1
      end
    end

    while off_a < part_a.size
      array << part_a[off_a]
      off_a += 1
    end

    while off_b < part_b.size
      array << part_b[off_b]
      off_b += 1
    end

    array
  end
end

由于它是作为Ruby模块实现的,因此可以将它包含在Array类中:

Array.send(:include, ParallelMergeSort)


[1, 2, 5, 6, 8, 10, 33, 4, 33, 44, 1, 100, 87].merge_sorted #=> [1, 1, 2, 4, 5, 6, 8, 10, 33, 33, 44, 87, 100]

回到你的问题。如果仔细观察提到线程的那一行。我在新的Array中创建了两个新的Threads,在它们内部进行计算然后我#join()一起线程并从它们中检索#value()。由于Array中总有两个线程,因此我可以将结果解包为变量part_apart_b