Guest User

Untitled

a guest
Jun 18th, 2018
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.22 KB | None | 0 0
  1. # asynchronous_object.rb
  2. #
  3. # Copyright © 2009 Preston Lee. All rights reserved.
  4.  
  5. require 'thread'
  6.  
  7. class AsychronousObject
  8.  
  9. attr_reader :thread
  10. attr_reader :update_frequency
  11. attr_reader :last_updated
  12.  
  13. def initialize(freq)
  14. @update_freqency = freq
  15. # puts @update_freqency
  16. @mutex = Mutex.new
  17.  
  18. start
  19. end
  20.  
  21. def start
  22. @last_updated = Time.now
  23. @state = :active # or :inactive
  24. # puts @mutex
  25. @thread = Thread.new do
  26. keep_going = true
  27. while keep_going do
  28. @mutex.synchronize do
  29. # puts "going"
  30. keep_going = false if @state == :inactive
  31. end
  32. if keep_going
  33. now = Time.now
  34. # puts "TL '#{@last_updated}' N #{now} F #{@update_freqency}"
  35. update(@last_updated, now)
  36. @last_updated = now
  37. sleep @update_freqency
  38. end
  39. end
  40. end
  41. end
  42.  
  43. def update
  44. puts "FAIL!"
  45. raise "You need to implement this method!"
  46. end
  47.  
  48. def activate
  49. @mutex.synchronize do
  50. case @state
  51. when :active
  52. # do nothing
  53. when :inactive
  54. start
  55. end
  56. end
  57. end
  58.  
  59. def deactivate
  60. @mutex.synchronize do
  61. @state = :inactive
  62. end
  63. end
  64.  
  65. def join
  66. @thread.join
  67. end
  68.  
  69. end
Add Comment
Please, Sign In to add comment