Created
February 12, 2019 09:37
-
-
Save ayuLiao/dc9a1b04053499295b986ad40bfbccef to your computer and use it in GitHub Desktop.
利用fcntl实现文件锁 在uwsgi的环境下,因为uwsgi会开启多个python进行接收请求,此时要求并发请求时,某些步骤单步执行,就需要使用外部锁,而不是使用进程内的逻辑锁,最简单的外部锁就是文件锁,使用fcntl,实现文件锁会非常简单。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import fcntl | |
class Lock(object): | |
def __init__(self, filename): | |
self.filename = filename | |
self.handle = open(filename,'w') | |
def acquire(self): | |
# if you need a non-blocking lock, use fcntl.LOCK_NB | |
fcntl.flock(self.handle, fcntl.LOCK_EX) | |
def release(self): | |
fcntl.flock(self.handle, fcntl.LOCK_UN) | |
def __del__(self): | |
self.handle.close() | |
''' | |
flask 对应的请求方法,当多个请求来时,调用该方法,将其变为单步执行 | |
''' | |
def filelocktest(): | |
try: | |
lock = Lock('./deploy_lock.tmp') | |
lock.acquire() | |
time.sleep(5) | |
print('filelock is running') | |
finally: | |
lock.release() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment