【发布时间】:2023-03-29 03:29:01
【问题描述】:
我有一个运行长任务的 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
如果你启动你的瓶子应用程序并继续 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.
我当然错过了多进程逻辑中的某些内容,但我找不到什么。知道发生了什么吗?
【问题讨论】:
标签: python multiprocessing bottle