quattro_4 scribble

scribble 落書き (調べた事をただ落書きする)

RubyTapas #141 - #146

141 Bounded Queue

set a maximum size on our queue class

def initialize(max_size = :infinite)
...
def full?
  return false if @max_size == :infinite
  @max_size <= @items.size
end

condition_predicate

wait_for_condition(
  @item_available,
  ->{@items.any?},

142 Infinity

1.0 / 0                         # => Infinity
Float::INFINITY                 # => Infinity

def initialize(max_size = Float::INFINITY)

benign value

benign 〔影響や効果が〕無害な、安全な 親切な、温暖な benignの意味・用例|英辞郎 on the WEB:アルク

143 Thread Interruptions

shutting down threads by setting a $shutdown flag

t = Thread.new do
...
t.raise "Abort!"
result = t.join rescue $!

Thread Interruptions

bt = catch((klass||ExitException).new) do |exception|
...
rescue (klass||ExitException) => e

Thread.handle_interrupt

Thread.handle_interrupt(RuntimeError => :never) do
Thread.handle_interrupt(RuntimeError => :immediate) do
Thread.handle_interrupt(RuntimeError => :on_blocking) do

Exception root class

Thread.handle_interrupt(Exceptions => :on_blocking) do ... end

these methods are the Kanye West of Ruby concurrency

Kanye West ?

144 Bulk Generation

codes = []
200.times do
  codes << SecureRandom.hex(8)
end

but I'm never satisfied

codes = 200.times do
...
codes                           # => 200

codes = 200.times.map { SecureRandom.hex(8) }
codes = 200.times.collect { SecureRandom.hex(8) }

この場合だけcollect使いたい

145 Thread Pool

WorkQueue

@jobs    = TapasQueue.new(10)
@threads = thread_count.times.map {|worker_num|
  Thread.new do
    dispatch(worker_num)

compute_batch

def compute_batch(thread_count, numbers)
  work_queue   = WorkQueue.new(thread_count)
  answer_queue = TapasQueue.new(10)
  solutions    = {}

benchmark

Benchmark.bm(3) do |b|
$ rvm jruby do ruby pool.rb 

146 Monitor

state-of-the-art turtle-recognition system

"recursive locking" deadlock
Ruby's mutexes are not recursive
Recursion-aware mutexes require more code and memory than a basic mutex

monitor library

require "monitor"
include MonitorMixin
def initialize
  super
...
def update(turtle, score)
  synchronize do