Итерационная обработка данных потоками
Суть программы в следующем:считать очередное число, обработка его первым потоком и помещение результата в массив номер 1, потом второй поток берет следующее число из очереди и обрабатывает его, используя предыдущее посчитанное значение потоком 1. Проблема в том, что оба потока запускаются только 1 раз.
import matplotlib.pyplot as plt
import threading
from collections import deque
from cmath import cosh, sinh
import random as rd
def write_complex(name):
a = -20
b = 20
numbers = [(rd.randint(a, b), rd.randint(a, b)) for i in range(20)]
with open(name, 'w') as file:
for re, im in numbers:
file.write(f'{re}:{im}\n')
def read_complex(name: str):
with open(name, 'r') as file:
array = [line.strip().split(':') for line in file.readlines()]
return deque([complex(float(re), float(im)) for re, im in array])
def f1(e, q: deque, f1_res, f2_res):
if e.is_set():
e.wait(0.5)
e.set()
res = q.pop() - f2_res[-1]
f1_res.append(res)
e.clear()
def f2(e, q: deque, f1_res, f2_res):
if e.is_set():
e.wait(0.5)
e.set()
res = q.pop() - f1_res[-1]
f2_res.append(res)
e.clear()
name = 'complex.dat'
write_complex(name)
q = read_complex(name) # read data
res1, res2 = [], [complex(rd.randint(-20, 20), rd.randint(-20, 20))]
e = threading.Event()
t1 = threading.Thread(target=f1, args=(e, q, res1, res2))
t2 = threading.Thread(target=f2, args=(e, q, res1, res2))
t1.start()
t2.start()
print(res1)
print(res2)