from concurrent.futures import ThreadPoolExecutor,as_completed
import threading
# 并发的轮子
class ConcurrentTest:
# 这里一般就设置结果字典、并发锁、其他通用内容
def __init__(self):
self.results_map = {}
self.lock = threading.Lock()
self.devices = {"device_1","device_2","device_3"}
# 固定要写一个测试方法
def _run_container(self,serial):
return {"status":"success","serial":serial}
# 固定一个跑的方法
def run(self):
# 设置一个查找字典
future_to_device = {}
# 设置连接池
with ThreadPoolExecutor(max_workers=3) as executor:
for device in self.devices:
future = executor.submit(self._run_container,device)
future_to_device[future] = device
for future in as_completed(future_to_device):
try:
res = future.result()
with self.lock:
self.results_map[future_to_device[future]] = {"status":res["status"]}
except Exception as e:
print(f"{future_to_device[future]} run fail : {e}")
# 必须保证数据契约的完整性,不管成功失败,下游一定要拿到对应的 key
with self.lock:
self.results_map[future_to_device[future]] = {"status": "ERROR"}