在 Bottle 应用程序中使用多进程创建多个 Bottle 实例

Use of multiprocess in a Bottle app create multiple bottle instance

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

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

例子

main.py

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)

functions.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

如果你启动你的 bottle 应用并访问 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.

我肯定错过了多进程逻辑中的某些内容,但我找不到。知道发生了什么事吗?

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

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