I have a python setup multiprocessing(i.e. workflows) with custom signal processing, which prevents the worker from using cleanly multiprocessing. (See details of the problem below.)
Customization
The master class , which generates all workflows, looks as follows (some parts are divided only into important parts).
Here he re-links his own signalprint-only Master teardown; actually received signals propagate through the process tree and must be processed by the workers themselves. This is achieved by re-linking the signals after the appearance of workers.
class Midlayer(object):
def __init__(self, nprocs=2):
self.nprocs = nprocs
self.procs = []
def handle_signal(self, signum, frame):
log.info('Master teardown')
for p in self.procs:
p.join()
sys.exit()
def start(self):
for _ in range(nprocs):
p = Worker()
self.procs.append(p)
p.start()
signal.signal(signal.SIGINT, self.handle_signal)
signal.signal(signal.SIGTERM, self.handle_signal)
for p in self.procs:
p.join()
multiprocessing.Process run() -.
. : SIGINT SIGTERM. ; , , ( quit_req True).
class Worker(Process):
def __init__(self):
self.quit_req = False
Process.__init__(self)
def handle_signal(self, signum, frame):
print('Stopping worker (pid: {})'.format(self.pid))
self.quit_req = True
def run(self):
signal.signal(signal.SIGINT, self.handle_signal)
signal.signal(signal.SIGTERM, self.handle_signal)
q = connect_to_some_distributed_message_queue()
print('Starting worker (pid: {})'.format(self.pid))
while not self.quit_req:
message = q.poll()
if len(message):
try:
print('{} handling message "{}"'.format(
self.pid, message)
)
MessageRouter.route(message)
except Exception as e:
print('{} failed handling "{}": {}'.format(
self.pid, message, e.message)
)
, () :
: ( message MessageRouter) -, .
, , - :
nproc = 4
p = Pool(processes=nproc)
rpx = [p.apply_async(some_expensive_calculation, ()) for _ in range(nproc)]
res = [rpx.get(timeout=.5) for r in rpx]
print(res)
, Pool, SIGINT SIGTERM handle_signal (- ), Stopping worker (pid: ...) . , - , , .
: , , ( ), , ( ) . , multiprocessing .
, ( , ) , .
- ? - ? , - , !