A Smallest Example for Multi-threading in Python with Event and Lock

Thanks to Jacob Zhong’s help. This is quite useful!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61

from flask import Flask
import threading
import time
import random

data = []
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 run
produce.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 (*/ω\*)