繁体   English   中英

python2 和 python3 multiprocessing.process 问题

[英]python2 and python3 multiprocessing.process issue

我试图了解多处理模块中 python2 和 python3 之间的变化。 在 python2 上运行此代码就像一个魅力:

def RunPrice(items, price):
    print("There is %s items, price is: %s" % (items, price))

def GetTargetItemsAndPrice(cursor):
    res = cursor.execute("SELECT DISTINCT items, price FROM SELLS")
    threads = []
    for row in res.fetchall():
        p = multiprocessing.Process(target=RunPrice, args=(row[0],row[1]))
        threads.append(p)
        p.start()
    for proc in threads:
        proc.join()

假设有 2000 个条目要在 SELLS 中处理。 在 python2 上,此脚本按预期运行并退出。 在 python3 上,我得到一个:

  File "/usr/lib/python3.8/multiprocessing/popen_fork.py", line 69, in _launch
    child_r, parent_w = os.pipe()
OSError: [Errno 24] Too many open files

知道python2和python3之间发生了什么吗?

我假设您的实际RunPrice函数比您显示的更RunPrice CPU。 否则,这将不是多处理的好选择。 如果RunPrice非常RunPrice CPU 并且不放弃 CPU 以等待 I/O 完成,那么当您考虑创建进程时,拥有一个进程池比您拥有的 CPU 内核数更多的处理池将是RunPrice不是特别便宜的操作(尽管肯定不会像在 Windows 上运行时那样昂贵)。

from multiprocessing import Pool

def RunPrice(items, price):
    print("There is %s items, price is: %s" % (items, price))

def GetTargetItemsAndPrice(cursor):
    res = cursor.execute("SELECT DISTINCT items, price FROM SELLS")
    rows = res.fetchall()
    MAX_POOL_SIZE = 1024
    # if RunPrice is very CPU-intensive, it may not pay to have a pool size
    # greater than the number of CPU cores you have. In that case:
    #from multiprocessing import cpu_count
    #MAX_POOL_SIZE = cpu_count()
    pool_size = min(MAX_POOL_SIZE, len(rows))
    with Pool(pool_size) as pool:
        # return values from RunPrice:
        results = pool.starmap(RunPrice, [(row[0], row[1]) for row in rows])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM