【问题标题】:How to synchronize progression bar with multiprocessing如何将进度条与多处理同步
【发布时间】:2021-01-14 14:41:41
【问题描述】:

我有一个 VueJs 前端,一个 python Flask 后端,我正在使用 Google Firebase 数据库..

在某些任务中,会向用户显示进度条。为了实现bar,后端将累进值写入数据库,前端读取。

我更改了后端,因为它太慢了,所以我使用 multiprocessing.Pool 并行化了一些操作。我有一个很好的性能提升,但现在进度条有时会继续,然后又回来,因为有更多的进程正在访问 db。

我在这里创建池:

i = 1
num_workers = multiprocessing.cpu_count()
pool = multiprocessing.Pool(processes=num_workers)
for filename in glob.glob(os.path.join(files_path, '*')):


    pool.apply_async(create_single_model, (filename, models_path, num_model_photos, uid, i))
    print('Process: ' + str(i))
    i = i + 1

create_single_model 中的我通过 i 并递增它,但我认为它不正确。:

.
some operations...
.

percentage = round((i / num_model_photos) * 100)
i = i + 1
ref = fb.db.collection('users').document(uid).get()
actual_percentage = ref.to_dict()['running']
if percentage != actual_percentage:
    fb.db.collection('users').document(uid).set({
        'running': percentage
    }, merge=True)

【问题讨论】:

    标签: python firebase google-cloud-firestore multiprocessing


    【解决方案1】:

    看起来每个子流程都在计算自己的进度,而不是整体进度。您需要一个可供每个子流程访问的共享变量来存储整体进度。完成工作后,每个子流程都可以将该变量加 1。

    按照这个答案:
    Sharing a counter with multiprocessing.Pool

    我想出了一个简单的例子:

    import time
    from multiprocessing import Pool, Value
    
    
    def some_func(n):
        for _ in range(n):
            with cnt.get_lock():
                cnt.value += 1
                print('\r{:.0%}'.format(cnt.value / 100), end='')
                time.sleep(0.1)
    
    
    def init_globals(counter):
        global cnt
        cnt = counter
    
    
    if __name__ == "__main__":
        counter = Value('i', 0)
    
        with Pool(initializer=init_globals, initargs=(counter,), processes=2) as pool:
            multi_results = pool.starmap(some_func, [(50,), (50,)])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-29
      • 1970-01-01
      • 2023-03-09
      • 1970-01-01
      • 2023-04-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-13
      相关资源
      最近更新 更多