pythonfcntl文件鎖

此模塊只有在 unix 系統(tǒng)上才有,windows 沒(méi)有。

創(chuàng)新互聯(lián)于2013年創(chuàng)立,是專業(yè)互聯(lián)網(wǎng)技術(shù)服務(wù)公司,擁有項(xiàng)目網(wǎng)站制作、網(wǎng)站建設(shè)網(wǎng)站策劃,項(xiàng)目實(shí)施與項(xiàng)目整合能力。我們以讓每一個(gè)夢(mèng)想脫穎而出為使命,1280元興化做網(wǎng)站,已為上家服務(wù),為興化各地企業(yè)和個(gè)人服務(wù),聯(lián)系電話:18980820575

文檔地址:

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

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

多進(jìn)程示例程序
import fcntl
import os
import time
from multiprocessing import Pool

def worker():
    print('task: %s' % os.getpid())
    try:
        f = open('scheduler.lock', 'wb')
        '''加鎖,同步鎖,其他進(jìn)程獲取不到需等待'''
        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 詳細(xì)參數(shù)
'''f 需傳入文件對(duì)象,operator 傳入加鎖方式'''
fcntl.flock(f, operator)

fcntl.LOCK_SH    '共享鎖'
fcntl.LOCK_EX    '排他鎖'
fcntl.LOCK_NB    '非阻塞鎖——如果指定此參數(shù),函數(shù)不能獲得文件鎖就立即返回,否則,函數(shù)會(huì)等待獲得文件鎖。LOCK_NB可以同LOCK_SH或LOCK_NB進(jìn)行按位或(|)運(yùn)算操作。 fcntl.flock (f,fcntl.LOCK_EX|fcntl.LOCK_NB)'
fcntl.LOCK_UN    '解鎖'
解決 gunicorn flask-apscheduler 重復(fù)執(zhí)行問(wèn)題
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()

    '''注冊(cè)一個(gè)退出回調(diào)函數(shù),用于在程序退出時(shí)進(jìn)行一些清理工作,關(guān)閉文件,解除鎖'''
    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 '<h2>Hello World!</h2>'

新聞標(biāo)題:pythonfcntl文件鎖
轉(zhuǎn)載來(lái)于:http://muchs.cn/article20/ipiijo.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供移動(dòng)網(wǎng)站建設(shè)、網(wǎng)站導(dǎo)航、手機(jī)網(wǎng)站建設(shè)、品牌網(wǎng)站設(shè)計(jì)網(wǎng)站策劃、網(wǎng)站改版

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)

h5響應(yīng)式網(wǎng)站建設(shè)