Python 多进程文件共享变量。

不羁岁月 提交于 2020-01-25 21:57:56
# -*- coding: utf-8 -*-
# usr/bin/python3.6.7

# @idea      :PyCharm 
# @FileName  :moreThread.py
# @Time      :2019/12/31 16:12
# @Author    :zzq
import time
import os
from multiprocessing import Process, Lock

class Read1(Process):

    def __init__(self, obj, ):
        super(Read1, self).__init__()
        self.obj = obj

    def run(self):
        self.readFile()
        print(self.name, time.time(),  os.getpid())

    def readFile(self):
        while True:
            time.sleep(0.1)
            self.obj.acquire()
            with open("a", 'r') as f:
                self.num = f.read()
            self.num = int(self.num)
            self.num += 1
            if self.num < 100:
                with open("a", 'w') as f:
                    f.write(str(self.num))
                self.obj.release()
                print("%s--->%s" % (self.name, self.num))
            else:
                self.obj.release()
                break

        return


class Read2(Process):

    def __init__(self, obj ):
        super(Read2, self).__init__()
        self.obj = obj

    def run(self):
        self.readFile()
        print(self.name, time.time(), os.getpid())

    def readFile(self):
		while True:
			time.sleep(0.1)
            self.obj.acquire()
            with open("a", 'r') as f:
                self.num = f.read()
            self.num = int(self.num)
            self.num += 1
            if self.num < 100:
                with open("a", 'w') as f:
                    f.write(str(self.num))
                self.obj.release()
                print("%s--->%s" % (self.name, self.num))
            else:
                self.obj.release()
                break




if __name__ == "__main__":
    lock = Lock()
    with open('a', 'w') as f:
        f.write(str(0))
    time.sleep(2)
    Read1(lock).start()
    Read2(lock).start()

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!