Skip to content

Instantly share code, notes, and snippets.

@lnznt
Created January 16, 2015 20:21
Show Gist options
  • Save lnznt/5671c51cb2f43babd664 to your computer and use it in GitHub Desktop.
Save lnznt/5671c51cb2f43babd664 to your computer and use it in GitHub Desktop.
$ ruby t1.rb
hello # 子スレッドで表示
hello # 〃
hello # 〃
$ ruby t2.rb
hello # メインスレッドで表示
hello # 〃
hello # 〃
$ ruby t3.rb
hello(1) # メインスレッドで表示 (以下、同じ)
hello(2)
hello(1)
hello(1)
hello(2)
hello(1)
hello(1)
hello(1)
hello(2)
hello(1)
$ ruby t5.rb
--> child
hello
hello
--> main
--> child
hello
hello
--> main
--> child
hello
hello
--> main
th = Thread.new { 3.times { puts "hello" ; sleep 1 } }
th.join # メインスレッドが終了しないように子スレッドを待つ
q = Queue.new
th = Thread.new { loop { q << "hello" ; sleep 1 } }
3.times { puts q.pop }
q = Queue.new
m = Mutex.new # Mutex で Queue を排他ロックする
class << m
alias call synchronize # ロックは synchronize でかけるが
end # 名前が長いのでここでは call に alias した
th1 = Thread.new { loop { m.() { q << "hello(1)" } ; sleep 1 } }
th2 = Thread.new { loop { m.() { q << "hello(2)" } ; sleep 3 } }
10.times { puts q.pop }
require 'socket'
require 'resolv-replace' # この require により、Ruby が割り込みを行えるように
# DNS名前解決に resolv ライブラリを使うようにする
require 'timeout'
begin
sock = timeout(10) { TCPSocket.open 'localhost', 80 }
rescue TimeoutError => e # タイムアウトした場合 TimeoutError 例外があがる
$stderr.puts e
end
p sock
require 'socket'
require 'resolv-replace'
require 'timeout'
# タイムアウトも含めコネクトできない場合はすべて sock を nil にする
sock = timeout(10) { TCPSocket.open 'localhost', 80 } rescue nil
p sock
require 'fiber' # Fiber#transfer 等を使用する場合に require が必要。
# この例では、この require はなくてよい
f = Fiber.new do
loop do
2.times { puts "hello" ; sleep 1 }
puts "--> main" ; Fiber.yield # Fiber.#yield で元のファイバにコンテキストを戻す
end
end
3.times { puts "--> child" ; f.resume } # resume メソッドでファイバにコンテキストを切り替え
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment