Answer the question
In order to leave comments, you need to log in
Answer the question
In order to leave comments, you need to log in
Instead of it is necessary to close flows and processes from the outside. You can get in a lot of trouble.
In a well-designed solution, threads / processes themselves should be closed when necessary. If you need to manage this from the outside, then for this there are primitives such as semaphores / flags / events.
It is useful to put any search or preparation of pieces of a common solution into streams. In this case, you can use two template primitives: "collector" and "winner":
"Collector":
import threading
def job(id, ...):
global res
<Подготовка блока данных>
res[id] = <блок подготовленных данных>
return
res = []
for i in range(N): # запуск N потоков
res.append(<пустой блок>)
threading.Thread(target=job, args=(i, ...)).start()
for th in threading.enumerate(): # ожидание всех потоков
if th != threading.currentThread():
th.join()
<здесь массив с блоками полностью собран >
import threading
def job(...):
global val
global event
while <не нашли>
<элементарный шаг поиска>
if event.is_set():
return # кто-то уже нашел искомое
val=<то что нашли>
event.set() # этот поток нашел искомое и радостно сообщает всем об этом
return
val = None # искомое значение
event = threading.Event() # флаг сигнализирующий о том что решение найдено
threads = []
for i in range(N):
threads.append(threading.Thread(target=job, args=(i, ...)))
threads[-1].start()
event.wait() # тут основной поток ждет сигнала о победе от одного из запущенных потоков
# если есть шанс, что победителя может и не быть, то в wait() нужно указать таймаут
# и читать значение event.wait(), что бы узнать - сработал таймаут или появился победитель.
<тут обрабатываем найденное>
for th in threads: # Подчищаем за собой - гарантированно собираем закрывшиеся потоки
th.join()
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question