Python 多進程文件共享變量。

# -*- 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()

發佈了25 篇原創文章 · 獲贊 6 · 訪問量 6223
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章