Multithreading 芹菜工人与多线程-如何同步更新结果
我和一个芹菜工人创建了一个烧瓶API。用户触发“开始测试”按钮,该按钮发出POST请求,返回url,用户可以使用该url每隔5秒获取测试结果(需要更新fontend进度条)。芹菜任务包括穿线。我的目标是根据线程的结果同时更新芹菜任务状态。我不想等到所有线程都完成后才返回结果。我的芹菜任务如下所示:Multithreading 芹菜工人与多线程-如何同步更新结果,multithreading,queue,celery,Multithreading,Queue,Celery,我和一个芹菜工人创建了一个烧瓶API。用户触发“开始测试”按钮,该按钮发出POST请求,返回url,用户可以使用该url每隔5秒获取测试结果(需要更新fontend进度条)。芹菜任务包括穿线。我的目标是根据线程的结果同时更新芹菜任务状态。我不想等到所有线程都完成后才返回结果。我的芹菜任务如下所示: @celery.task(bind=True) # bind argument instructs Celery to send a "self" argument and use it to re
@celery.task(bind=True) # bind argument instructs Celery to send a "self" argument and use it to record status updates
def run_tests(self, dialog_cases):
"""
Testing running as a background task
"""
results = []
test_case_no = 1
test_controller = TestController(dialog_cases)
bot_config = [test_controller.url, test_controller.headers, test_controller.db_name]
threads = []
queue = Queue()
start = time.perf_counter()
threads_list = list()
for test_case in test_controller.test_cases:
t = Thread(target=queue.put({randint(0,1000): TestCase(test_case, bot_config)}))
t.start()
threads_list.append(t)
for t in threads_list:
t.join()
results_dict_list = [queue.get() for _ in range(len(test_controller.test_cases))]
for result in results_dict_list:
for key, value in result.items():
cprint.info(f"{key}, {value.test_failed}")
现在:TestCase是一个对象,它在创建时运行一个函数,进行一些迭代,然后返回测试是否失败或通过。我有另一个Flask端点,它返回任务的状态。问题是如何同时获得线程返回的值,而不必等到它们全部完成?我尝试了排队,但这只能在一切结束时返回结果 您只需使用修改任务的状态,如果这是您想要的,可以从每个线程修改任务的状态。此外,您还可以创建自己的。由于您希望在每个测试完成时就知道其结果,因此最好为教学测试设置一个自定义状态,并在运行时从每个线程更新该状态
另一种方法是重构代码,使每个测试实际上都是一项芹菜任务。然后使用或分组原语来构建工作流。因为您想在运行时了解状态,所以Group可能更好,因为这样您就可以监视GroupResult对象的状态…如果您已经在使用芹菜,为什么不使用它的并发/排队功能,而不是自己实现它呢?那和弦呢?谢谢你的帮助-最后我决定放弃芹菜,转而使用另一种方法,保存每次测试的结果(每个线程)在Mongodb中,连同POST方法中提供的“id”,我创建了一个端点,返回特定测试id的结果嗯,如果你不需要分配你的任务,那么就不需要芹菜之类的东西。。。