Skip to content

@nicksieger /concurrent.rb
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
JRuby code examples from RailsConf 2011
require 'java'
java_import java.util.concurrent.Executors
@count = java.util.concurrent.atomic.AtomicInteger.new
def send_email(executor)
executor.submit do
puts "email #{@count.incrementAndGet} sent"
end
end
executor = Executors.newCachedThreadPool
send_email(executor)
executor = Executors.newFixedThreadPool(2)
10.times do
send_email(executor)
end
#!/usr/local/bin/ruby
BAILOUT = 16
MAX_ITERATIONS = 1000
class Mandelbrot
def initialize
puts "Rendering"
for y in -39...39 do
puts
for x in -39...39 do
i = iterate(x/40.0,y/40.0)
if (i == 0)
print "*"
else
print " "
end
end
end
end
def iterate(x,y)
cr = y-0.5
ci = x
zi = 0.0
zr = 0.0
i = 0
while(1)
i += 1
temp = zr * zi
zr2 = zr * zr
zi2 = zi * zi
zr = zr2 - zi2 + cr
zi = temp + temp + ci
return i if (zi2 + zr2 > BAILOUT)
return 0 if (i > MAX_ITERATIONS)
end
end
end
(ARGV[0] || 1).to_i.times {
time = Time.now
Mandelbrot.new
puts
puts "Ruby Elapsed %f" % (Time.now - time)
}
require 'benchmark'
require 'digest/md5'
TEN_MEGABYTES = 1048576 * 10
class WorkerTask
def initialize(data, range)
@data, @range = data, range
end
def run
@thread = Thread.new do
50.times do
digest = Digest::MD5.new
@range.step(1024) do |idx|
digest.update(@data[idx...idx+1024])
end
end
end
end
def join
@thread.join
end
end
puts RUBY_DESCRIPTION
#puts "Reading 10MB of data..."
data = File.open('/dev/urandom') {|f| f.read(TEN_MEGABYTES)}
def create_tasks(data, number)
tasks = []
(0...data.length).step(data.length / number) do |idx|
task = WorkerTask.new(data, idx...(idx + (data.length / number)))
task.run
tasks << task
end
tasks
end
2.times do
tasks = []
Benchmark.bm(20) do |bm|
bm.report('serial') { create_tasks(data, 1).each {|t| t.join} }
bm.report('2 threads') { create_tasks(data, 2).each {|t| t.join} }
bm.report('8 threads') { create_tasks(data, 8).each {|t| t.join} }
bm.report('512 threads') { create_tasks(data, 512).each {|t| t.join} }
end
end
#!/bin/bash
ruby-1.8.7-p302 $@
ruby-1.9.2-p136 $@
jruby-head $@
M, N = (ARGV[0] || "100").to_i, (ARGV[1] || "1000").to_i
def make_array
threads = []
data = []
M.times do |m|
threads << Thread.new do
N.times do |n|
data << m * n
end
end
end
threads.each {|t| t.join }
data
end
100.times do |i|
begin
data = make_array
unexpected = data.select {|x| x.nil?}.size
puts "Run #{'%2d' % (i+1)}: Made an array of #{data.size} numbers"
puts "Run #{'%2d' % (i+1)}: array has #{unexpected} nil entries" if unexpected > 0
rescue => e
puts "Run #{'%02d' % (i+1)}: #{e.class}: #{e.message}"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.