【问题标题】:How can I dynamically create new process in python?如何在 python 中动态创建新进程?
【发布时间】:2018-06-27 11:28:07
【问题描述】:

这是我的主要功能。如果我收到新的报价,我需要检查付款。我有 HandleNewOffer() 函数。但是,如果同时有 2 个(或更多)报价,则会出现此代码的问题。其中一位买家将不得不等到交易结束。那么这是否可以使用 HandleNewOffer() 函数生成新进程并在完成同时进行多个事务时将其杀死?先感谢您。

def handler():
    try:
        conn = k.call('GET', '/api/').json() #connect
        response = conn.call('GET', '/api/notifications/').json() 
        notifications = response['data']
        for notification in notifications:
            if notification['contact']:
                HandleNewOffer(notification) # need to dynamically start new process if notification

    except Exception as err:
        error= ('Error')
        Send(error)

【问题讨论】:

  • 可能你想使用线程而不是进程,或者在这里使用异步编程

标签: python asynchronous process multiprocessing subprocess


【解决方案1】:

我建议在这里使用 Pool of workers 模式来限制并发调用数量为 HandleNewOffer

concurrent.futures 模块提供了上述模式的现成实现。

from concurrent.futures import ProcessPoolExecutor

def handler():
    with ProcessPoolExecutor() as pool:
        try:
            conn = k.call('GET', '/api/').json() #connect
            response = conn.call('GET', '/api/notifications/').json() 

            # collect notifications to process into a list
            notifications = [n for n in response['data'] if n['contact']]

            # send the list of notifications to the concurrent workers
            results = pool.map(HandleNewOffer, notifications)

            # iterate over the list of results from every HandleNewOffer call
            for result in results:
                print(result)
        except Exception as err:
            error= ('Error')
            Send(error)

此逻辑将并行处理与计算机拥有的 CPU 内核一样多的报价。

【讨论】:

    猜你喜欢
    • 2018-04-15
    • 1970-01-01
    • 2011-05-28
    • 1970-01-01
    • 2022-08-14
    • 2018-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多