Skip to content

Instantly share code, notes, and snippets.

@dzil123
Created September 26, 2019 06:24
Show Gist options
  • Save dzil123/4174105b06a1f6b5c4e43c40cf1afde5 to your computer and use it in GitHub Desktop.
Save dzil123/4174105b06a1f6b5c4e43c40cf1afde5 to your computer and use it in GitHub Desktop.
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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment