Class: GHArchive::ThreadPool

Inherits:
Object
  • Object
show all
Defined in:
lib/gh-archive.rb

Instance Method Summary collapse

Constructor Details

#initialize(size) ⇒ ThreadPool



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/gh-archive.rb', line 14

def initialize(size)
    @size = size
    @threads = []
    @queue = []
    @mutex = Mutex.new
    
    @consumer_thread = Thread.start do
        while !@shutdown || @threads.size > 0 || @queue.size > 0
            sleep 0.1 if @queue.size == 0 || @threads.size == @size
            @threads.delete_if { |t| !t.alive? }
            
            if @threads.size < @size && @queue.size > 0
                @mutex.synchronize do
                    args, job = @queue.shift
                    @threads << Thread.start(*args, &job)
                end
            end
        end
    end
end

Instance Method Details

#alive?Boolean



65
66
67
# File 'lib/gh-archive.rb', line 65

def alive?
    @consumer_thread.alive?
end

#enqueuedObject



57
58
59
# File 'lib/gh-archive.rb', line 57

def enqueued
    return @queue.size
end

#process(*args, &block) ⇒ Object



35
36
37
38
39
40
41
42
43
44
# File 'lib/gh-archive.rb', line 35

def process(*args, &block)
    raise "Block expected" unless block_given?
    raise "Can not add jobs while shutting down" if @shutdown
    
    @mutex.synchronize do
        @queue << [args, block]
    end
    
    return self.enqueued
end

#shutdownObject



46
47
48
# File 'lib/gh-archive.rb', line 46

def shutdown
    @shutdown = true
end

#shutdown!Object



50
51
52
53
54
55
# File 'lib/gh-archive.rb', line 50

def shutdown!
    self.shutdown
    @mutex.synchronize do
        @queue.clear
    end
end

#shutdown?Boolean



61
62
63
# File 'lib/gh-archive.rb', line 61

def shutdown?
    @shutdown
end

#waitObject



69
70
71
72
73
# File 'lib/gh-archive.rb', line 69

def wait
    while alive?
        sleep 0.1
    end
end