Created
February 27, 2013 08:48
-
-
Save tsyber1an/5046400 to your computer and use it in GitHub Desktop.
some sort of examples 'how to use threads
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$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; } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://blog.engineyard.com/2011/a-modern-guide-to-threads