forked from your-tools/python-cli-ui
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththreads.py
More file actions
55 lines (42 loc) · 1.1 KB
/
Copy paththreads.py
File metadata and controls
55 lines (42 loc) · 1.1 KB
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
import threading
import time
from threading import Thread
import cli_ui
def long_computation():
# Simulates a long computation
time.sleep(0.6)
def count_down(lock, start):
x = start
while x >= 0:
with lock:
# Note: the sleeps are here so that we are more likely to
# see mangled output
#
# In reality, if you only call `ui.info()` once you don't
# need locks at all thanks to the GIL
cli_ui.info("down", end=" ")
time.sleep(0.2)
cli_ui.info(x)
time.sleep(0.2)
long_computation()
x -= 1
def count_up(lock, stop):
x = 0
while x <= stop:
with lock:
cli_ui.info("up", end=" ")
time.sleep(0.2)
cli_ui.info(x)
time.sleep(0.2)
long_computation()
x += 1
def main():
lock = threading.Lock()
t1 = Thread(target=count_down, args=(lock, 4))
t2 = Thread(target=count_up, args=(lock, 4))
t1.start()
t2.start()
t1.join()
t2.join()
if __name__ == "__main__":
main()