Fiber:
counts = Hash.new(0)
File.foreach("D:/rails.txt") do |line|
line.scan(/\w+/) do |word|
word = word.downcase
counts[word] += 1
end
end
counts.keys.sort.each{ |k| puts "#{k}:#{counts[k]}"}
###########################################################
words = Fiber.new do
File.foreach("D:/rails.txt") do |line|
line.scan(/\w+/) do |word|
Fiber.yield word.downcase
end
end
end
counts = Hash.new(0)
while word = words.resume
counts[word] += 1
end
counts.keys.sort.each{ |k| puts "#{k}:#{counts[k]}"}
另外的例子:
twos = Fiber.new do
num = 2
loop do
Fiber.yield(num) unless num % 3 == 0
num += 2
end
end
10.times { print twos.resume, " " }
多线程:
require 'net/http'
pages = %w( www.sina.com.cn www.yahoo.com www.sohu.com )
threads = []
for page_to_fetch in pages
threads << Thread.new(page_to_fetch) do |url|
h = Net::HTTP.new(url, 80)
print "Fetching: #{url}\n"
resp = h.get('/')
print "Got #{url}: #{resp.message}\n"
end
end
threads.each { |thr| thr.join }
Race Condition (来自Ruby编程的代码,但是在测试时没有发现Ruby1.9.3)
def inc(n)
n+1
end
sum = 0
threads = (1..10).map do
Thread.new do
10_000.times do
sum = inc(sum)
end
end
end
threads.each(&:join)
p sum
据说应该使用Mutex来锁住对象以防止race condition
def inc(n)
n+1
end
sum = 0
mutex = Mutex.new
threads = (1..10).map do
Thread.new do
10_000.times do
mutex.lock
sum = inc(sum)
mutex.unlock
end
end
end
threads.each(&:join)
p sum
Ruby调用Window API
require 'win32ole'
$urls = []
def navigate(url)
$urls << url
end
def stop_msg_loop
puts "IE has exited..."
throw :done
end
def default_handler(event, *args)
case event
when "BeforeNavigate"
puts "Now Navigating to #{args[0]}..."
end
end
ie = WIN32OLE.new('InternetExplorer.Application')
ie.visible = TRUE
#ie.gohome
ie.navigate("http://www.baidu.com")
ev = WIN32OLE_EVENT.new(ie, 'DWebBrowserEvents')
ev.on_event {|*args| default_handler(*args)}
ev.on_event("NavigateComplete") {|url| navigate(url)}
ev.on_event("Quit") {|*args| stop_msg_loop}
catch(:done) do
loop do
WIN32OLE_EVENT.message_loop
end
end
puts "You Navigated to the following URLs: "
$urls.each_with_index do |url, i|
puts "(#{i+1}) #{url}"
end
自己写Ruby扩展:
http://www.rubyinside.com/how-to-create-a-ruby-extension-in-c-in-under-5-minutes-100.html
http://extensions.rubyforge.org/rdoc/index.html