Skip to content

Instantly share code, notes, and snippets.

@tsyber1an
Created February 27, 2013 08:48
Show Gist options
  • Save tsyber1an/5046400 to your computer and use it in GitHub Desktop.
Save tsyber1an/5046400 to your computer and use it in GitHub Desktop.
some sort of examples 'how to use threads
require 'thread'
require 'net/http'
urls = ["http://slonweb.ru", "https://github.com", "http://www.ruby-doc.org/core-2.0/Thread.html"]
threads = []
responses = []
responses_mutex = Mutex.new
urls.each do |url|
threads << Thread.new(url) do |url|
response = Net::HTTP.get_response URI.parse(url)
responses_mutex.synchronize { responses << response }
end
end
threads.each(&:join)
$buffer = {}
$bufflock = Mutex.new
threads = (0..2).map do |i|
Thread.new do
puts "Starting Thread #{i}"
3.times do
puts "Thread #{i} got: #{$buffer[:foo].inspect}"
$bufflock.synchronize{ $buffer[:foo] = ($buffer[:foo] || 1) * (i+1) }
sleep rand
end
puts "Ending Thread #{i}"
end
end
threads.each{ |t| t.join; }
threads = []
(1..5).each do |i|
threads << Thread.new { Thread.current[:output] = `echo Hi from thread ##{i}` }
end
threads.each do |t|
t.join
puts t[:output]
end
require 'net/http'
pages = %w( www.rubycentral.com
www.awl.com
www.pragmaticprogrammer.com
)
threads = []
for page in pages
threads << Thread.new(page) { |myPage|
h = Net::HTTP.new(myPage, 80)
puts "Fetching: #{myPage}"
resp, data = h.get('/', nil )
puts "Got #{myPage}: #{resp.message}"
}
end
threads.each { |aThread| aThread.join }
@tsyber1an
Copy link
Author

@tsyber1an
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment