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.



42
43
44
45
46
47
48
49
50
51
# File 'src/ruby/lib/grpc/generic/rpc_server.rb', line 42

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



54
55
56
# File 'src/ruby/lib/grpc/generic/rpc_server.rb', line 54

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



62
63
64
65
66
67
68
69
70
71
72
# File 'src/ruby/lib/grpc/generic/rpc_server.rb', line 62

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.



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

def start
  @stop_mutex.synchronize do
    fail 'already stopped' if @stopped
  end
  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



91
92
93
94
95
96
97
98
99
100
# File 'src/ruby/lib/grpc/generic/rpc_server.rb', line 91

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