Guest User

Untitled

a guest
Dec 11th, 2018
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.99 KB | None | 0 0
  1. require 'thread'
  2.  
  3. class ThreadPool
  4. attr_reader :size
  5.  
  6. def initialize size = 24
  7. @size = size
  8. @queue = Queue.new
  9. @pool = size.times.collect do
  10. Thread.new do
  11. catch :exit do
  12. loop do
  13. job, args = queue.deq
  14. job.call *args
  15. end
  16. end
  17. end
  18. end
  19. end
  20.  
  21. def submit *args, &block
  22. queue.enq [block, args]
  23. end
  24.  
  25. def shutdown timeout = nil
  26. size.times do
  27. submit do
  28. throw :exit
  29. end
  30. end
  31.  
  32. if timeout
  33. shutdown_with_timeout timeout
  34. else
  35. pool.each &:join
  36. end
  37.  
  38. queue.clear
  39. @size = 0
  40. end
  41.  
  42. def status
  43. {
  44. :size => size,
  45. :threads => pool.map(&:status),
  46. :queue => {
  47. :size => queue.size,
  48. :consumers => queue.num_waiting,
  49. },
  50. }
  51. end
  52.  
  53. private
  54. attr_reader :queue, :pool
  55.  
  56. def shutdown_with_timeout timeout
  57. Timeout.timeout timeout.to_i do
  58. pool.each &:join
  59. end
  60. rescue Timeout::Error
  61. pool.each &:kill
  62. end
  63. end
Add Comment
Please, Sign In to add comment