Class: ThreadPool
- Inherits:
-
Object
- Object
- ThreadPool
- Defined in:
- lib/threadpool.rb
Instance Attribute Summary collapse
-
#queue ⇒ Object
readonly
Returns the value of attribute queue.
-
#size ⇒ Object
readonly
Returns the value of attribute size.
Instance Method Summary collapse
-
#execute(*args, &job) ⇒ Object
Schedules a
jobto be run with the givenargs. -
#initialize(size) ⇒ ThreadPool
constructor
Creates a new ThreadPool with
sizethreads, waiting at your beck and call. -
#schedule(*args, &job) ⇒ Object
Schedules a
jobto be run with the givenargs. -
#shutdown ⇒ Object
Cleans up after the ThreadPool, quitting and joining all remaining threads.
Constructor Details
#initialize(size) ⇒ ThreadPool
Creates a new ThreadPool with size threads, waiting at your beck and call.
9 10 11 12 13 14 15 |
# File 'lib/threadpool.rb', line 9 def initialize(size) self.size = size self.queue = Queue.new # create a pool of threads the size requested self.pool = Array.new(size) { thread } end |
Instance Attribute Details
#queue ⇒ Object
Returns the value of attribute queue.
3 4 5 |
# File 'lib/threadpool.rb', line 3 def queue @queue end |
#size ⇒ Object
Returns the value of attribute size.
2 3 4 |
# File 'lib/threadpool.rb', line 2 def size @size end |
Instance Method Details
#execute(*args, &job) ⇒ Object
Schedules a job to be run with the given args. Returns only once the queue of jobs to be performed is empty.
This is primarily intended for preventing front-loading an arbitraril large number of jobs into the queue. However, it works simply by calling Thread.pass until the queue is empty. This has the disadvantage of spinning the processor the all the threads are mostly waiting on I/O or sleeping. It also means that if other threads are scheduling jobs, this may never return.
Ideally, this method would pause the current thread until the job has begun execution, but this is surprisingly difficult to do with the Ruby built-in Queue class, which we use for the job queue.
39 40 41 42 43 |
# File 'lib/threadpool.rb', line 39 def execute(*args, &job) self.schedule(*args, &job) Thread.pass until self.queue.empty? end |
#schedule(*args, &job) ⇒ Object
Schedules a job to be run with the given args. Returns immediately.
20 21 22 |
# File 'lib/threadpool.rb', line 20 def schedule(*args, &job) self.queue.push [job, args] end |
#shutdown ⇒ Object
Cleans up after the ThreadPool, quitting and joining all remaining threads. No more jobs can be run in the pool once this method has been called.
50 51 52 53 |
# File 'lib/threadpool.rb', line 50 def shutdown self.size.times { self.schedule { Thread.exit } } self.pool.each {|thread| thread.join } end |