pybottle gunicorn gevent 不共享全局字典

pybottle gunicorn gevent not sharing global dict

from gevent import monkey
monkey.patch_all()

import bottle

app = bottle.Bottle()
COUNT = 0

@app.route('/inc', method='GET')
def count():
    global COUNT
    COUNT += 1
    return COUNT

def main():
    app.run(
        server="gunicorn",
        host="0.0.0.0",
        port=port,
        workers=50,
        worker_class="gevent",
        debug=False,
        reloader=False,
    )

if __name__ == '__main__':
    main(sys.argv[1:])

当我刷新 0.0.0.0/inc 时,它不是线性增加,而是从 1 到 0 到 1 到 0 到 2 到 1 到 0,等等

这告诉我每个线程(gevent worker)维护 COUNT 值

如何在所有 gevent worker 之间共享全局变量?

-- 我确认确实单独的 greenlet 正在跟踪它自己的 COUNT

INFO:__main__:(<Greenlet at 0x7fcae40bbd00: _handle_and_close_when_done(functools.partial(<bound method GeventWorker.handl, <bound method StreamServer.do_close of <StreamServ, (<gevent._socket3.socket at 0x7fcae256ebe0 object,)>) COUNT 1
INFO:__main__:(<Greenlet at 0x7fcae40bbd00: _handle_and_close_when_done(functools.partial(<bound method GeventWorker.handl, <bound method StreamServer.do_close of <StreamServ, (<gevent._socket3.socket at 0x7fcae256ebe0 object,)>) COUNT 2
INFO:__main__:(<Greenlet at 0x7fcae40bbd00: _handle_and_close_when_done(functools.partial(<bound method GeventWorker.handl, <bound method StreamServer.do_close of <StreamServ, (<gevent._socket3.socket at 0x7fcae256ebe0 object,)>) COUNT 3
INFO:__main__:(<Greenlet at 0x7fcae40bbd00: _handle_and_close_when_done(functools.partial(<bound method GeventWorker.handl, <bound method StreamServer.do_close of <StreamServ, (<gevent._socket3.socket at 0x7fcae256ebe0 object,)>) COUNT 4
INFO:__main__:(<Greenlet at 0x7fcae40bbd00: _handle_and_close_when_done(functools.partial(<bound method GeventWorker.handl, <bound method StreamServer.do_close of <StreamServ, (<gevent._socket3.socket at 0x7fcae409fa00 object,)>) COUNT 1
    app.run(
        server='gevent',
        host="0.0.0.0",
        port=port
    )

删除 gunicorn 对我有用