Guest User

Untitled

a guest
Jan 17th, 2018
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.76 KB | None | 0 0
  1. class ThreadPool
  2. def initialize(num_threads)
  3. @tasks = Queue.new # contains either blocks to run, or :terminate
  4. @threads = []
  5. @terminated = false # only used to stop new work from being enqueued
  6. num_threads.times do
  7. @threads << Thread.new{ process }.run
  8. end
  9. end
  10.  
  11. def run(&block)
  12. raise "cannot add new work while awaiting completion" if @terminated
  13. @tasks << block
  14. end
  15.  
  16. def await_completion
  17. @terminated = true
  18. @threads.count.times do
  19. @tasks << :terminate
  20. end
  21. @threads.each do |thread|
  22. thread.join
  23. end
  24. end
  25.  
  26. private
  27. def process
  28. # worker thread run loop
  29. while true
  30. item = @tasks.pop # will block if nothing in task queue
  31. break if item == :terminate
  32. item[]
  33. end
  34. end
  35. end
Add Comment
Please, Sign In to add comment