python fcntl 文件鎖

此模塊只有在 unix 系統上纔有,windows 沒有。html

文檔地址:python

https://docs.python.org/3.7/library/fcntl.htmlflask

https://www.docs4dev.com/docs/zh/python/3.7.2rc1/all/library-fcntl.htmlwindows

多進程示例程序

import fcntl
import os
import time
from multiprocessing import Pool

def worker():
    print('task: %s' % os.getpid())
    try:
        f = open('scheduler.lock', 'wb')
        '''加鎖,同步鎖,其餘進程獲取不到需等待'''
        fcntl.flock(f, fcntl.LOCK_EX)
        print('I am get file %s' % os.getpid())
        time.sleep(10)
        '''解鎖'''
        fcntl.flock(f, fcntl.LOCK_UN)
        f.close()
    except Exception as e:
        print('file is already locked: %s' % os.getpid())

if __name__ == '__main__':
    p = Pool(4)
    for i in range(5):
        p.apply_async(worker)
    print('Waiting for all subprocesses done...')
    p.close()
    p.join()
    print('All subprocesses done.')

fcntl 詳細參數

'''f 需傳入文件對象,operator 傳入加鎖方式'''
fcntl.flock(f, operator)

fcntl.LOCK_SH    '共享鎖'
fcntl.LOCK_EX    '排他鎖'
fcntl.LOCK_NB    '非阻塞鎖——若是指定此參數,函數不能得到文件鎖就當即返回,不然,函數會等待得到文件鎖。LOCK_NB能夠同LOCK_SH或LOCK_NB進行按位或(|)運算操做。 fcntl.flock (f,fcntl.LOCK_EX|fcntl.LOCK_NB)'
fcntl.LOCK_UN    '解鎖'

解決 gunicorn flask-apscheduler 重複執行問題

from flask import Flask
from service.extensions import scheduler
import logging
from logging.handlers import RotatingFileHandler
import os
import fcntl, atexit

basedir = os.path.abspath('')

def create_app():
    app = Flask(__name__)

    f = open("scheduler.lock", "wb")
    try:
        '''使用非阻塞鎖'''
        fcntl.flock(f, fcntl.LOCK_EX | fcntl.LOCK_NB)
        register_apscheduler(app)
    except Exception as e:
        pass

    def unlock():
        fcntl.flock(f, fcntl.LOCK_UN)
        f.close()

    '''註冊一個退出回調函數,用於在程序退出時進行一些清理工做,關閉文件,解除鎖'''
    atexit.register(unlock)

    return app

def register_apscheduler(app):
    scheduler.init_app(app)
    from service import aliyuncron
    scheduler.start()

app = create_app()

@app.route('/')
def index():
    return '<h1>Hello World!</h1>'
相關文章
相關標籤/搜索