How to use tqdm through multi process in python?

谁说我不能喝 提交于 2019-12-03 12:50:46

Generally, each process has its own data, independent of every other process. Spawning a new process (which calls os.fork on Unix) creates a copy of the current process. Each process obtains its own copy of all global values (such as pbar). Each process's global variables may share the same names as variables in the other processes, but each can hold an independent value.

In your case it looks like you want just one pbar to exist, and all calls to update should update that one pbar. So create pbar in only one process, and use a Queue to send signals to that process to update pbar:

import multiprocessing as mp

SENTINEL = 1

def test(q):
    for i in range(10000):
        sleep(0.1)
        q.put(SENTINEL)

def listener(q):
    pbar = tqdm(total = 10000)
    for item in iter(q.get, None):
        pbar.update()

if __name__ == '__main__':
    q = mp.Queue()
    proc = mp.Process(target=listener, args=(q,))
    proc.start()
    workers = [mp.Process(target=test, args=(q,)) for i in range(5)]
    for worker in workers:
        worker.start()
    for worker in workers:
        worker.join()
    q.put(None)
    proc.join()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!