Class: XThreads::XThread

Inherits:
Object
  • Object
show all
Defined in:
lib/xthreads.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, options = {}, &blk) ⇒ XThread

Returns a new instance of XThread.



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/xthreads.rb', line 15

def initialize(name, options={}, &blk)
  opts = {interval: 4, loop: true}.merge(options)
  @name = name
  @initialized = true
  @state = :stop

  @thread = Thread.new do 
    puts "#{name} created\n"
    Thread.current['name'] = name
    loop = true
    while loop == true do
      
      if @state == :start then
        @result = blk.call
        @state = :dead
        loop = false if opts[:loop] == false
      else
        puts 'stopped' unless @initialized == true
        @initialized = false
      end 

      Thread.stop if @state == :stop

      sleep opts[:interval]
    end
  end

end

Instance Attribute Details

#resultObject (readonly)

Returns the value of attribute result.



13
14
15
# File 'lib/xthreads.rb', line 13

def result
  @result
end

#stateObject (readonly)

Returns the value of attribute state.



13
14
15
# File 'lib/xthreads.rb', line 13

def state
  @state
end

Instance Method Details

#killObject



55
56
57
58
59
# File 'lib/xthreads.rb', line 55

def kill
  puts 'XThread killed'
  @thread.kill
  @state = :dead
end

#startObject



44
45
46
47
48
# File 'lib/xthreads.rb', line 44

def start
  puts "#{@name} starting ..."
  @state = :start
  @thread.run
end

#stopObject



50
51
52
53
# File 'lib/xthreads.rb', line 50

def stop
  puts "'#{@name}' stopping ..."
  @state = :stop
end

#threadObject



61
62
63
# File 'lib/xthreads.rb', line 61

def thread
  @thread
end