A Smallest Example for Multi-threading in Python with Event and Lock Posted on 2019-01-22 | Edited on 2019-02-04 | In Code | | Views: Symbols count in article: 1.3k | Reading time ≈ 1 mins. Thanks to Jacob Zhong’s help. This is quite useful! 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061from flask import Flaskimport threadingimport timeimport randomdata = []signal = threading.Event()lock = threading.Lock()class Random(threading.Thread): def __init__(self): threading.Thread.__init__(self) def run(self): while True: n = random.random() # print("Produces", n) lock.acquire() data.append(n) lock.release() if len(data) >= 10: signal.set() time.sleep(0.1)class Sum(threading.Thread): def __init__(self): threading.Thread.__init__(self) def run(self): while True: signal.wait() with lock: # print("\nConsumes", sum(data)) data.clear() time.sleep(0.1) signal.clear()# create new produce = Random()consume = Sum()# start to runproduce.start()consume.start()def create_app(): # create and configure the app app = Flask(__name__, instance_relative_config=True) # a simple page that says hello @app.route('/hello') def hello(): with lock: return str(data[0]) return app Like the author (*/ω\*) Donate WeChat Pay Alipay