守护进程不允许创建子进程。

12

我知道这是一个常见的问题,与这个类似的问题,但我想询问最适合我的情况的最佳方法,因为我现在还没有使用过 celery。

我的服务场景将使用multiprocessing.Process创建多个广告活动订单,在每个广告活动订单中,它仍然使用multiprocessing.Process创建多个广告(广告活动和广告之间是1对M的关系)。

如您所知,如果我在广告活动和广告创建部分都设置了多进程,它会失败并显示“daemonic processes are not allowed to have children”,我认为即使我现在还没有使用它,celery也可能会遇到类似的问题。

我的问题是,解决这种问题的一般方法是什么? 我应该继续使用 celery,还是有任何方法可以解决它?

非常感谢

1个回答

4

1. 通用的好方法

你应该使用消息队列来解耦

例如:

  1. 主程序创建任务,将其推送到队列1中

  2. 多活动工作线程从队列1中获取任务,处理并将一些“多广告任务”推送到队列2中

  3. 多广告工作线程从队列2中获取任务,处理完成。

这个逻辑很简单,易于自己实现。此外,还有一些现有的库可用于此类操作,例如rq/celery

2. 简单的解决方法

如果出现AssertionError,请使用线程代替。

def run_in_subprocess(func, *args, **kwargs):
    from multiprocessing import Process
    thread = Process(target=func, args=args, kwargs=kwargs)
    thread.daemon = True
    thread.start()
    return thread

def run_in_thread(func, *args, **kwargs):
    from threading import Thread
    thread = Thread(target=func, args=args, kwargs=kwargs)
    thread.daemon = True
    thread.start()
    return thread

def run_task(config):
    try:
        run_in_subprocess(xxxx_task, config)
    except AssertionError:
        print('daemonic processes are not allowed to have children, use thread')
        run_in_thread(xxxx_task, config)

我在一些演示应用程序中使用了这段代码,但不建议在生产环境中使用。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接