首页 > 解决方案 > 在一个瓶子应用程序中使用多进程创建多个瓶子实例

问题描述

我有一个运行很长任务的 Bottle Web 应用程序,为了赢得一些时间,我使用了多处理池。在 webapp 之外(所以只在我的 IDE 中运行代码)看起来不错,从 54 秒到 14 秒。但是如果我在我的 webapp 上下文中运行我的多处理函数,它只会显示 X 次(X 对应于我的池大小):

Bottle v0.12.18 server starting up (using WSGIRefServer())...

例子

主文件

from bottle import route, run
from functions import runFunction


@route('/')
def index():
    runFunction()
    return "<b>Hello</b>!"

run(host='localhost', port=8083,debug=False, reloader=True)

函数.py

import multiprocessing as mp
import time
import random

def longTask(x):
    print(mp.current_process())
    y = random.randint(1,5)
    print(y)
    time.sleep(y)
    return x**x

def runFunction():
    start_time = time.time()
    pool = mp.Pool(3)
    result = pool.map(longTask, [4, 2, 3, 5, 3, 2, 1, 2])
    print(result)
    
if __name__ == '__main__':
    runFunction()

如果只在 functions.py 中运行 main,则输出为:

<SpawnProcess(SpawnPoolWorker-1, started daemon)>
1
<SpawnProcess(SpawnPoolWorker-3, started daemon)>
4
<SpawnProcess(SpawnPoolWorker-2, started daemon)>
2
<SpawnProcess(SpawnPoolWorker-1, started daemon)>
1
<SpawnProcess(SpawnPoolWorker-1, started daemon)>
2
<SpawnProcess(SpawnPoolWorker-2, started daemon)>
1
<SpawnProcess(SpawnPoolWorker-2, started daemon)>
1
<SpawnProcess(SpawnPoolWorker-1, started daemon)>
2
[256, 4, 27, 3125, 27, 4, 1, 4]

Process finished with exit code 0

如果你启动你的瓶子应用程序并继续 http://localhost:8083/ 它将输出:

Bottle v0.12.18 server starting up (using WSGIRefServer())...
Listening on http://localhost:8083/
Hit Ctrl-C to quit.

Bottle v0.12.18 server starting up (using WSGIRefServer())...
Listening on http://localhost:8083/
Hit Ctrl-C to quit.

Bottle v0.12.18 server starting up (using WSGIRefServer())...
Listening on http://localhost:8083/
Hit Ctrl-C to quit.

我当然错过了多进程逻辑中的一些东西,但我找不到什么。知道发生了什么吗?

标签: pythonmultiprocessingbottle

解决方案


main.py文件是multiprocessing在进程启动期间导入的,所有新进程通过调用生成新的瓶服务器run(host=...。只需确保run在导入文件时不执行:

if __name__ == '__main__':
    run(host='localhost', port=8083,debug=False, reloader=True)

推荐阅读