python fcntl 文件鎖

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

文檔地址:

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

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

多進程示例程序

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>'
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章