t.rb

L Nicoara, 05/01/2014 09:51 PM

Download (996 Bytes)

 
1
#!/usr/bin/env ruby
2

    
3
class ThreadPool
4
    attr_accessor :size, :threads, :jobs
5

    
6
    def initialize(size)
7
        @size    = size
8
        @jobs    = Queue.new
9
        @threads = create_threads
10
    end
11

    
12
    def create_threads
13
        @size.times.map do |i|
14
            Thread.start do
15
                Thread.current[:id] = i
16

    
17
                catch(:thread_quit) do
18
                    loop do
19
                        job, args = @jobs.pop
20
                        job.call *args
21
                    end
22
                end
23
            end
24
        end
25
    end
26

    
27
    def join
28
        threads.each &:join
29
    end
30

    
31
    def shutdown
32
        size.times do
33
            add { throw :thread_quit }
34
        end
35

    
36
        threads.map &:join
37
    end
38

    
39
    def add(*args, &job)
40
        jobs << [job, args]
41
    end
42

    
43
    def queue_size;
44
        jobs.size
45
    end
46
end
47

    
48

    
49
loop do
50
    pool = ThreadPool.new 2
51

    
52
    128.times do |i|
53
        pool.add(i) do |i|
54
            sleep 0.001
55
        end
56
    end
57

    
58
    pool.join
59
end