Month: July 2014
Thread pool in the minimum of code…
Presentation
Thread creation / join / exit can be heavy in cpu ressources.
So here en thread manager in a few lines of code.
Creation
def pool_create(size)
@queue=Queue.new
size.times { Thread.new { loop {
param,bloc=@queue.pop
bloc.call(param) rescue p $!
} } }
end
the thread pool can be use with pool_get(parameter) { code }
:
def pool_get(param,&block)
sleep(0.1) while @queue.num_waiting<3
@queue.push([param,block])
end
using pool
if you used to do :
def run(socket)
Thread.new(socket) do |io|
request(io)
end
end
replace it by :
def run(socket)
pool_get(socket) do |io|
request(io)
end
end
This tool is used in femtows : web server in 260 lines of codes 🙂