Class: LimitedFork

Inherits:
Object
  • Object
show all
Includes:
Singleton
Defined in:
lib/limitedfork.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeLimitedFork

Returns a new instance of LimitedFork.



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/limitedfork.rb', line 7

def initialize
    @pids = 0
    @max_processes = 10 # arbitrary default
    @mutex=Mutex.new

    trap("CHLD") do
        begin
            loop do
                pid = Process.wait(0)
                @mutex.synchronize do
                    # @pids -= [ pid ]
                    @pids -= 1
                end
            end
        rescue Errno::ECHILD
            @pids = 0
        end
    end
end

Instance Attribute Details

#max_processesObject

Returns the value of attribute max_processes.



27
28
29
# File 'lib/limitedfork.rb', line 27

def max_processes
  @max_processes
end

#mutexObject

Returns the value of attribute mutex.



27
28
29
# File 'lib/limitedfork.rb', line 27

def mutex
  @mutex
end

#pidsObject

Returns the value of attribute pids.



27
28
29
# File 'lib/limitedfork.rb', line 27

def pids
  @pids
end

Class Method Details

.forkObject



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/limitedfork.rb', line 41

def self.fork
    if pids > instance.max_processes then
        # block until it's okay to go
        begin
            pid = Process.waitpid
            instance.mutex.synchronize do
                # instance.pids -= [ pid ]
                self.pids -= 1
            end
        rescue Errno::ECHILD
            # Oops, look like someone already got there.  Never
            # mind then!
            self.pids=0
        end
    end

    pid = Process.fork { yield }
    if pid
        instance.mutex.synchronize do
            instance.pids += 1
        end
    end
    return pid
end

.limit=(limit) ⇒ Object



37
38
39
# File 'lib/limitedfork.rb', line 37

def self.limit=(limit)
    instance.max_processes=limit
end

.pidsObject



29
30
31
# File 'lib/limitedfork.rb', line 29

def self.pids
    instance.pids
end

.pids=(val) ⇒ Object



33
34
35
# File 'lib/limitedfork.rb', line 33

def self.pids=(val)
    instance.pids=val
end