1. uwsgi 的锁
来源:https://stackoverflow.com/questions/42325105/flask-processing-requests-1-by-1
如果使用的是 uwsgi
,那么可以使用下面的锁
@app.route("/",methods=['POST'])
def main_process():
uwsgi.lock()
# Critical section
# heavy process here to run alone
uwsgi.unlock()
return "Done"
根据 https://github.com/unbit/uwsgi/issues/2309 的说法,uwsgi
的锁是全局进程锁,在 core/lock.c
中可以看到锁操作是在共享内存中进行的。
官方文档:https://uwsgi-docs.readthedocs.io/en/latest/Locks.html
uWSGI supports a configurable number of locks you can use to synchronize worker processes. Lock 0 (zero) is always available, but you can add more with the locks option. If your app has a lot of critical areas, holding and releasing the same lock over and over again can kill performance.
def use_lock_zero_for_important_things():
uwsgi.lock() # Implicit parameter 0
# Critical section
uwsgi.unlock() # Implicit parameter 0
def use_another_lock():
uwsgi.lock(1)
time.sleep(1) # Take that, performance! Ha!
uwsgi.unlock(1)
2. python 层面的线程锁
import threading
mutex = threading.RLock()
try:
mutex.acquire()
print("hello world")
except Exception as e:
pass
finally:
mutex.release()