Мое первоначальное предположение состоит в том, что причина зависания процесса заключалась в том, что он использовал очередь, и в конце очередь не была пуста и закрыта. Освобождение и закрытие очереди предотвращает проблему (демо 3 ниже), но этого также не происходит, когда в очереди несколько элементов, и она не пуста и не закрыта (демо 1 ниже). Так что я немного не в курсе.
Может ли кто-нибудь прояснить причину зависания процесса?
DEMO
- При использовании p = Process(target=some_function_that_does_not_break) вывод консоли следующий:
Function ended
queue size is=100
J1
J2
main ended
- При использовании p = Process(target=some_function_that_also_does_not_break) вывод консоли:
Function ended. Time filling queue: 1.999461717 seconds
Emptying queue
queue size is=3005706
J1
Queue empty! Time emptying queue: 26.81551289 seconds
Queue closed
J2
main ended
(Понятия не имею, почему очистка очереди занимает гораздо больше времени, чем ее заполнение)
- При использовании p = Process(target=some_function_that_breaks) вывод консоли будет
Function ended
queue size is=3152815
J1
(execution hanging here)
КОД
#!/usr/bin/env python
import time
from multiprocessing import Process, Queue, Value
q = Queue()
stop = Value("b", False)
# [EDIT]: I added the try...except... to prevent unnecessary comments
# about the queue being full, which should not happen since
# it does not have a max size.
def some_function_that_breaks():
print("Function started")
try:
while not stop.value:
q.put("Item")
except Exception as e:
print(f"Some exception happened: {e}")
print("Function ended")
def some_function_that_does_not_break(queue_size=100):
print("Function started")
for _ in range(queue_size):
q.put("Item")
print("Function ended")
def some_function_that_also_does_not_break():
print("Function started")
time_start = time.perf_counter_ns()
while not stop.value:
q.put("Item")
time_filling_s = (time.perf_counter_ns() - time_start) / 1e9
print(f"Function ended. Time filling queue: {time_filling_s} seconds")
print("Emptying queue")
time_start = time.perf_counter_ns()
while not q.empty():
q.get()
time_emptying_s = (time.perf_counter_ns() - time_start) / 1e9
print(f"Queue empty! Time emptying queue: {time_emptying_s} seconds")
q.close()
print("Queue closed")
p = Process(target=some_function_that_does_not_break)
p.start()
time.sleep(2)
stop.value = True
time.sleep(1)
print(f"queue size is={q.qsize()}")
print("J1")
p.join()
print("J2")
p.join()
print("main ended")
Подробнее здесь: https://stackoverflow.com/questions/790 ... ng-process