Skip to content

Instantly share code, notes, and snippets.

@pavelpatrin
Last active October 22, 2018 21:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pavelpatrin/a8284ec77490534abc449b6f364a53e1 to your computer and use it in GitHub Desktop.
Save pavelpatrin/a8284ec77490534abc449b6f364a53e1 to your computer and use it in GitHub Desktop.
Stupid multiprocessing
# coding: utf-8
import multiprocessing
import subprocess
import threading
import signal
import time
import os
# Убъет рабочий процесс пула через 5 секунд.
# К этому времени процесс получит задачу но не вернет результат.
# Количество отправленных задач никогда не сойдется с количеством полученных.
def killer():
print('Starting killer thread')
time.sleep(5)
command = 'ps --ppid %d | grep python' % os.getpid()
output = subprocess.check_output(command, shell=True)
chpid = int(output.split()[0])
print('Killing worker %d' % chpid)
os.kill(chpid, signal.SIGKILL)
thread = threading.Thread(target=killer)
thread.start()
# Запустит пул с одним процессом.
# Процесс с первой задачей будет убит через 5 секунд и никогда не вернет результат.
# Процесс со второй задачей успешно вернет результат через 10 секунд.
# Пул будет бесконечно ждать, пока количество отправленных и полученых задач не сойдется.
def worker(x):
print('Starting worker process %d' % os.getpid())
time.sleep(10)
print('Exiting worker process %d' % os.getpid())
return x
pool = multiprocessing.Pool(1)
for result in pool.imap_unordered(worker, [1, 2]):
print('Got result from worker: %r' % result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment