Class: Thread::Simple

Inherits:
Object show all
Defined in:
lib/overload/thread_simple.rb

Overview

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(size: 5, sleep: 0.05) ⇒ Simple

Returns a new instance of Simple.



19
20
21
22
23
24
25
26
# File 'lib/overload/thread_simple.rb', line 19

def initialize size: 5, sleep: 0.05
  @sync     = Mutex.new
  @sleep    = sleep
  @size     = size
  @que      = []
  @threds   = []
  @name_val = {}
end

Instance Attribute Details

#namedObject

Returns the value of attribute named.



17
18
19
# File 'lib/overload/thread_simple.rb', line 17

def named
  @named
end

#queObject

Returns the value of attribute que.



17
18
19
# File 'lib/overload/thread_simple.rb', line 17

def que
  @que
end

#sizeObject

Returns the value of attribute size.



17
18
19
# File 'lib/overload/thread_simple.rb', line 17

def size
  @size
end

Class Method Details

.run(**args) {|ts| ... } ⇒ Object

Thread::Simple.run do |t|

for foo in bar
  t.add { ... }
end

end

Yields:

  • (ts)


9
10
11
12
13
# File 'lib/overload/thread_simple.rb', line 9

def self.run **args
  ts = new
  yield ts
  ts.run
end

Instance Method Details

#[](name) ⇒ Object



62
63
64
# File 'lib/overload/thread_simple.rb', line 62

def [] name
  @name_val[name]
end

#add(name = nil, &block) ⇒ Object



28
29
30
31
32
33
34
35
36
# File 'lib/overload/thread_simple.rb', line 28

def add name = nil, &block
  @sync.synchronize do
    if name
      @que << proc { @name_val[name] = block.call }
    else
      @que << block
    end
  end
end

#run(endless: false) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/overload/thread_simple.rb', line 38

def run endless: false
  @endless = endless

  @size.times do
    @threds << Thread.new do
      task = nil

      while active?
        @sync.synchronize { task = @que.pop }
        task.call if task
        sleep @sleep
      end
    end
  end

  unless @endless
    @threds.each(&:join)
  end
end

#stopObject



58
59
60
# File 'lib/overload/thread_simple.rb', line 58

def stop
  @endless = false
end