python - 在一个瓶子应用程序中使用多进程创建多个瓶子实例
问题描述
我有一个运行很长任务的 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.
我当然错过了多进程逻辑中的一些东西,但我找不到什么。知道发生了什么吗?
解决方案
该main.py
文件是multiprocessing
在进程启动期间导入的,所有新进程通过调用生成新的瓶服务器run(host=...
。只需确保run
在导入文件时不执行:
if __name__ == '__main__':
run(host='localhost', port=8083,debug=False, reloader=True)
推荐阅读
- winapi - 如何将 IFileOperation 与相对路径和绝对路径一起使用?
- c++ - 通过引用与按值存储 shared_ptr?
- google-apps-script - 谷歌应用脚本:将活动幻灯片(谷歌幻灯片)导出为 PDF
- python - 如何在循环中重新映射/重新定义 python 函数列表?
- android - 在没有 WiFi 和 USB 的情况下在后台运行 adb logcat
- html - 如何在页面顶部插入 DIV 元素并向下滑动具有绝对 top:0 css 样式的其他元素
- node.js - MongoDB条件查找
- bash - bash 脚本中的命令无法使用变量输入
- android - GPUImage 在 Adreno GPU 上给出奇怪的输出,但在 Mali GPU 上工作正常
- qt - 如何在 qml 的标签中绘制视频?