您当前的位置: 首页 >  Python

彭世瑜

暂无认证

  • 1浏览

    0关注

    2791博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

Python:多进程下实现单例

彭世瑜 发布时间:2021-03-19 22:52:43 ,浏览量:1

通过一个判断文件是否存在,判断实例是否存在

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

import atexit
import os


@atexit.register
def remove_lock_file():
    if os.path.exists('file.lock'):
        os.remove('file.lock')


def create_lock_file():
    if not os.path.exists('file.lock'):
        with open('file.lock', 'w') as f:
            pass
        return True
    else:
        return False


from multiprocessing import Process


def open_file():
    if create_lock_file():
        print('hello')


Process(target=open_file).start()
Process(target=open_file).start()

两个进程下,只会打印一次hello

关注
打赏
1665367115
查看更多评论
立即登录/注册

微信扫码登录

0.0580s