Class: GRPC::Pool

Inherits:
Object
  • Object
show all
Defined in:
src/ruby/lib/grpc/generic/rpc_server.rb

Overview

Pool is a simple thread pool.

Constant Summary collapse

DEFAULT_KEEP_ALIVE =

Default keep alive period is 1s

1

Instance Method Summary collapse

Constructor Details

#initialize(size, keep_alive: DEFAULT_KEEP_ALIVE) ⇒ Pool

Returns a new instance of Pool


76
77
78
79
80
81
82
83
84
85
# File 'src/ruby/lib/grpc/generic/rpc_server.rb', line 76

def initialize(size, keep_alive: DEFAULT_KEEP_ALIVE)
  fail 'pool size must be positive' unless size > 0
  @jobs = Queue.new
  @size = size
  @stopped = false
  @stop_mutex = Mutex.new # needs to be held when accessing @stopped
  @stop_cond = ConditionVariable.new
  @workers = []
  @keep_alive = keep_alive
end

Instance Method Details

#jobs_waitingObject

Returns the number of jobs waiting


88
89
90
# File 'src/ruby/lib/grpc/generic/rpc_server.rb', line 88

def jobs_waiting
  @jobs.size
end

#schedule(*args, &blk) ⇒ Object

Runs the given block on the queue with the provided args.

Parameters:

  • args

    the args passed blk when it is called

  • blk

    the block to call


96
97
98
99
100
101
102
103
104
105
106
# File 'src/ruby/lib/grpc/generic/rpc_server.rb', line 96

def schedule(*args, &blk)
  return if blk.nil?
  @stop_mutex.synchronize do
    if @stopped
      GRPC.logger.warn('did not schedule job, already stopped')
      return
    end
    GRPC.logger.info('schedule another job')
    @jobs << [blk, args]
  end
end

#startObject

Starts running the jobs in the thread pool.


109
110
111
112
113
114
115
116
117
118
119
120
# File 'src/ruby/lib/grpc/generic/rpc_server.rb', line 109

def start
  fail 'already stopped' if @stopped
  until @workers.size == @size.to_i
    next_thread = Thread.new do
      catch(:exit) do  # allows { throw :exit } to kill a thread
        loop_execute_jobs
      end
      remove_current_thread
    end
    @workers << next_thread
  end
end

#stopObject

Stops the jobs in the pool


123
124
125
126
127
128
129
130
131
132
# File 'src/ruby/lib/grpc/generic/rpc_server.rb', line 123

def stop
  GRPC.logger.info('stopping, will wait for all the workers to exit')
  @workers.size.times { schedule { throw :exit } }
  @stop_mutex.synchronize do  # wait @keep_alive for works to stop
    @stopped = true
    @stop_cond.wait(@stop_mutex, @keep_alive) if @workers.size > 0
  end
  forcibly_stop_workers
  GRPC.logger.info('stopped, all workers are shutdown')
end