Skip to content
Browse files

static threads pool with queue

  • Loading branch information...
1 parent 5693474 commit 4df268b1699a6add6846fd73889df5e8e7f2039b @cocoa committed Feb 21, 2013
Showing with 54 additions and 0 deletions.
  1. +54 −0 lib/threadpool/threadpoolqueue.rb
View
54 lib/threadpool/threadpoolqueue.rb
@@ -0,0 +1,54 @@
+require 'thread'
+
+module Threadpool
+
+ class Tpoolqueue
+
+ def initialize(size)
+ @size = size
+ @jobs = Queue.new
+ @pool = Array.new(size) do |i|
+ Thread.new do
+ Thread.current[:id] = i
+ catch(:exit) do
+ loop do
+ job, args = @jobs.pop
+ job.call(*args)
+ end
+ end
+ end
+ end
+ end
+
+
+ def schedule(*args, &block)
+ @jobs << [block, args]
+ end
+
+
+ def shutdown
+ @size.times do
+ schedule { throw :exit }
+ end
+ @pool.map(&:join)
+ end
+
+ end
+
+
+ #########
+ # example
+ #########
+
+ p = Tpoolqueue.new(10)
+
+ 20.times do |i|
+ p.schedule do
+ sleep rand(4)+2
+ p "Job #{i} finished by thread #{Thread.current[:id]}"
+ end
+ end
+
+ at_exit {p.shutdown}
+
+end

0 comments on commit 4df268b

Please sign in to comment.
Something went wrong with that request. Please try again.