# -*- 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()
来源:CSDN
作者:qq_43355847
链接:https://blog.csdn.net/qq_43355847/article/details/103787285