Skip to content

Instantly share code, notes, and snippets.

@manveru
Forked from jcoene/gist:5034155
Last active December 18, 2015 03:19

Revisions

  1. manveru revised this gist Jun 5, 2013. 2 changed files with 16 additions and 20 deletions.
    20 changes: 0 additions & 20 deletions gistfile1
    Original file line number Diff line number Diff line change
    @@ -1,20 +0,0 @@
    #!/usr/bin/ruby

    # This program adds up the numbers 1 through 10,000 using 100 threads.

    # Challenge A: Does this solution have any problems? If so, explain.
    # Challenge B: Propose an alternate implementation that does not use threads.

    require "thread"

    mt_result = 0
    100.times.map do |n|
    Thread.new do
    base = 1 + (n * 100)
    100.times do |i|
    mt_result += base + i
    end
    end
    end.map(&:join)

    puts "The multi-threaded result is: #{mt_result}"
    16 changes: 16 additions & 0 deletions thread_sum.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,16 @@
    #!/usr/bin/env ruby

    threads = 100.times.map do |n|
    Thread.new n do |m|
    base = 1 + (m * 100)
    100.times.map do |i|
    base + i
    end
    end
    end

    result = threads.reduce(0) do |sum, thread|
    sum + thread.join.value.reduce(:+)
    end

    puts "The multi-threaded result is: #{result}"
  2. @jcoene jcoene created this gist Feb 25, 2013.
    20 changes: 20 additions & 0 deletions gistfile1
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,20 @@
    #!/usr/bin/ruby

    # This program adds up the numbers 1 through 10,000 using 100 threads.

    # Challenge A: Does this solution have any problems? If so, explain.
    # Challenge B: Propose an alternate implementation that does not use threads.

    require "thread"

    mt_result = 0
    100.times.map do |n|
    Thread.new do
    base = 1 + (n * 100)
    100.times do |i|
    mt_result += base + i
    end
    end
    end.map(&:join)

    puts "The multi-threaded result is: #{mt_result}"