Как не останавливать цикл и использовать потоки в методе
У меня на сокете должны производится вычисления которые повторяются в цикле метода main. Мне нужно сделать что бы цикл отработал быстрее. Что бы мы не ждали каждый расчет метода sendToFightCalc, так как не в игрушечном примере там расчет занимает секунд по 30. Как можно реализовать задуманное? Мне не обязательна чтобы main понимал что все расчеты сделаны, я добавлю счетчик и клиент будет обращаться к сокету с вопросом готовы ли все данные.
class ExapleTnh():
fight_result = {}
def addFightResult(self, hero, enemy, result):
self.fight_result[hero[0]] = {}
self.fight_result[hero[0]]['enemy'] = enemy[0]
self.fight_result[hero[0]]['win1'] = result[0]
self.fight_result[hero[0]]['win2'] = result[1]
def sendToFightCalc(self, hero, enemy):
#os.chdir("C:\\example")
#send_to_sub_proc = subprocess.run(f'java -cp blabla.jar hero "{hero}" enemy "{enemy}"',capture_output=True)
#response = send_to_sub_proc.stdout.decode('utf-8').split()[2]
response = [33, 25]
return response
def thread_navernoe(self, hero, enemy_hero):
result = self.sendToFightCalc(hero[1], enemy_hero[1])
self.addFightResult(hero, enemy_hero, result)
def main(self):
all_heroes = [['Nick1', 'Weapon'],['Nick2', 'Weapon'],['Nick3', 'Weapon'],['Nick4', 'Weapon']]
for hero in all_heroes:
#print('hero: ', hero)
for enemy_hero in all_heroes:
#print('enemy_hero: ', enemy_hero)
if {hero[0]} != {enemy_hero[0]}:
self.thread_navernoe(hero, enemy_hero)
return self
aa = ExapleTnh().main()
print(aa.fight_result)
Ответы (1 шт):
Автор решения: Incover
→ Ссылка
Потоки можно добавить в массив и в цикле подождать пока каждый завершится.
import threading
import time
class ExapleTnh():
threads = []
fight_result = {}
def addFightResult(self, hero, enemy, result):
self.fight_result[hero[0]] = {}
self.fight_result[hero[0]]['enemy'] = enemy[0]
self.fight_result[hero[0]]['win1'] = result[0]
self.fight_result[hero[0]]['win2'] = result[1]
def sendToFightCalc(self, hero, enemy):
# os.chdir("C:\\example")
# send_to_sub_proc = subprocess.run(f'java -cp blabla.jar hero "{hero}" enemy "{enemy}"',capture_output=True)
# response = send_to_sub_proc.stdout.decode('utf-8').split()[2]
response = [33, 25]
return response
def thread_navernoe(self, hero, enemy_hero):
result = self.sendToFightCalc(hero[1], enemy_hero[1])
self.addFightResult(hero, enemy_hero, result)
time.sleep(2)
def main(self):
all_heroes = [['Nick1', 'Weapon'], ['Nick2', 'Weapon'], ['Nick3', 'Weapon'], ['Nick4', 'Weapon']]
for hero in all_heroes:
for enemy_hero in all_heroes:
if {hero[0]} != {enemy_hero[0]}:
my_thread = threading.Thread(target=self.thread_navernoe, args=(hero, enemy_hero,))
my_thread.start()
self.threads.append(my_thread)#Добавляем поток
#Проверяем все ли потоки отработали
for my_thread in self.threads:
my_thread.join()
return self
aa = ExapleTnh().main()
print(aa.fight_result)