Skip to content

Commit 202c260

Browse files
committed
Threading\S08-Event\S08-01-Event
1 parent a4aef7d commit 202c260

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
# For Example : (Event Trigger)
2+
# 1) Task-main (Thread-Main) : define event as e
3+
# 2) Task1 (Thread1) : wait for e (blocking)
4+
# 3) Task2 (Thread2) : wait for e (non block)
5+
# 4) Task-main : e.set()
6+
# 5) Task1: trigger process
7+
# 6) Task2: trigger process
8+
9+
import threading
10+
import time
11+
12+
start = time.perf_counter()
13+
14+
15+
def task1(e):
16+
print(f'Task1 : Started ({round(time.perf_counter()-start)} Sec)')
17+
event_is_set = e.wait()
18+
print(f'Task1 : Resume => Event set: {event_is_set} ({round(time.perf_counter()-start)} Sec)')
19+
20+
21+
def task2(e, t):
22+
while not e.is_set():
23+
print(f'Task2 : Started ({round(time.perf_counter()-start)} Sec)')
24+
event_is_set = e.wait(t)
25+
print(f'Task2 : Resume (Non Blocking) => Event set: {event_is_set} ({round(time.perf_counter()-start)} Sec)')
26+
27+
if event_is_set: print(f'Task2 : Resume (Processing Event) ({round(time.perf_counter()-start)} Sec)')
28+
else: print(f'Task2 : Doing Somethings... ({round(time.perf_counter()-start)} Sec)')
29+
30+
31+
if __name__ == '__main__':
32+
e = threading.Event()
33+
34+
t1 = threading.Thread(name='Blocking', target=task1, args=(e,))
35+
t1.start()
36+
37+
t2 = threading.Thread(name='Non-blocking', target=task2, args=(e, 5))
38+
t2.start()
39+
40+
# t1.join()
41+
# t2.join()
42+
43+
print(f'Main Thread : Waiting before calling Event.set() ({round(time.perf_counter()-start)} Sec)')
44+
time.sleep(20)
45+
e.set()
46+
print(f'Main Thread : Event.set() ({round(time.perf_counter()-start)} Sec)')

0 commit comments

Comments
 (0)