帮助中心
  • 云主机
  • 数据盘
  • 弹性IP
  • 快照
  • 云防火墙

在共享目录(即比格云提供的共享存储)下,可使用文件锁来避免多线程或多进程下的并发竞争问题。共享存储为多客户端提供了统一名字空间的文件共享读写能力,但在多线程或多进程下可能会出现写覆盖、交叉、等异常状态。

解决方案:

文件锁+ seek 使用方法

python语言示例程序,仅供参考:

# -*- coding: utf-8 -*-


import time

import fcntl

 

def lock_file(fd):

    while True:

        try:

            fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)

            return

        except OSError:

            time.sleep(1)

 

def unlock_file(fd):

    try:

        fcntl.flock(fd, fcntl.LOCK_UN)

    except OSError:

        pass

 

def main(filename):

    file = open(filename, "a")

    fd = file.fileno()

 

    # Write the data into the file

    while True:

        # Lock the file

        lock_file(fd)

 

        file.seek(0, 2)

        file.write("the written data")

 

        # Unlock the file

        unlock_file(fd)

 

    # Close the file handler

    file.close()

上一篇 下一篇

技术交流企业群

点击发起工单