Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import threading
- import queue
- import time
- class Program:
- def __init__(self):
- self.queue = queue.Queue()
- self.pipeline = Pipeline(self)
- self.web = Webserver(self)
- def mainloop(self):
- while True:
- task = self.queue.get()
- task.run()
- class FifoLock:
- def __init__(self, program):
- self.program = program
- self.queue = self.program.queue
- self.condition = threading.Condition()
- # blocks until run() is called
- def __enter__(self):
- # equivalent to .acquire() ?
- self.condition.__enter__()
- self.queue.put(self)
- self.condition.wait()
- def __exit__(self, *exc_info):
- self.condition.notify_all()
- # equivalent to .release() ?
- self.condition.__exit__(*exc_info)
- # releases self from __enter__()
- # blocks until __exit__()
- def run(self):
- with self.condition:
- self.condition.notify_all()
- self.condition.wait()s
- class Pipeline:
- def __init__(self, program):
- self.program = program
- self.lock = FifoLock(self.program)
- def run(self):
- print("schedule p")
- with self.lock:
- print("pipeline")
- for x in range(3):
- print("p", x)
- time.sleep(.5)
- print("p exit")
- def mainloop(self):
- while True:
- self.run()
- class Webserver:
- def __init__(self, program):
- self.program = program
- self.lock = FifoLock(self.program)
- def run(self):
- print("schedule w")
- with self.lock:
- print("web")
- for x in range(3):
- print("w", x)
- time.sleep(.51234)
- print("w exit")
- p = Program()
- threading.Thread(target=p.mainloop).start()
- time.sleep(1)
- threading.Thread(target=p.pipeline.mainloop).start()
- time.sleep(5.34)
- threading.Thread(target=p.web.run).start()
- time.sleep(3.789)
- threading.Thread(target=p.web.run).start()
- time.sleep(5)
- import os
- os.abort()
- # Below is a runthrough
- $ python FifoLock.py
- schedule p
- pipeline
- p 0
- p 1
- p 2
- p exit
- schedule p
- pipeline
- p 0
- p 1
- p 2
- p exit
- schedule p
- pipeline
- p 0
- p 1
- p 2
- p exit
- schedule p
- pipeline
- p 0
- p 1
- schedule w
- p 2
- p exit
- schedule p
- web
- w 0
- w 1
- w 2
- w exit
- pipeline
- p 0
- p 1
- p 2
- p exit
- schedule p
- pipeline
- p 0
- schedule w
- p 1
- p 2
- p exit
- schedule p
- web
- w 0
- w 1
- w 2
- w exit
- pipeline
- p 0
- p 1
- p 2
- p exit
- schedule p
- pipeline
- p 0
- p 1
- Aborted (core dumped)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement