如何在python中动态创建新进程?

2024-04-19 08:17:24 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的主要职能。如果我收到新的报价,我需要检查付款情况。我有handlenewfer()函数。但如果同时有2个(或更多)报价,则会出现此代码的问题。其中一个买家必须等到交易结束。那么,是否可以使用handlenewfer()函数生成新的进程,并在同时执行多个事务时终止它?提前谢谢你。在

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)

Tags: 函数apijsongetifresponse情况notification
1条回答
网友
1楼 · 发布于 2024-04-19 08:17:24

我建议在这里使用workers池模式将并发调用的数量限制为HandleNewOffer。在

^{}模块提供上述模式的现成实现。在

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核并行的多个报价。在

相关问题 更多 >