Threading#
Sources#
Example1 - runtime messages#
In following exmaple:
Define the
myThread
class as an ancestor of thethreading.Thread
class - it will describe the behaviour of the thread:The
run
method is executed when the thread is started - in this case method:Spends time according to the
delay
parameter of the class;Increases the value of
counter
by one.
Create and run two instances of
myThread
:With
delay
0.5 and 1;With
name
“first” and “second”;
In cycle every 0.5 seconds check is threads still alife and print
counter
values for each instance;Result:
counter
of instance named “first” updated at each step;counter
of instance named “second” is updated once every two steps.
import threading
import time
steps_count = 5
class myThread(threading.Thread):
def __init__(self, delay, name):
super().__init__()
self.counter = 0
self.delay = delay
self.name = name
def run(self):
for i in range(steps_count):
time.sleep(self.delay)
self.counter += 1
threads = []
# Create new threads
thread1 = myThread(0.5, "first")
thread2 = myThread(1, "second")
begin_time = time.time()
# Start new Threads
thread1.start()
thread2.start()
# Add threads to thread list
threads.append(thread1)
threads.append(thread2)
is_any_thread_live = True
while is_any_thread_live:
time.sleep(0.5)
dislpay_line = \
f"====={round(time.time() - begin_time, 1)}" + \
" seconds after begining====="
print(dislpay_line)
for t in threads:
print(t.name + " counter = " + str(t.counter))
for t in threads:
if t.is_alive():
# if any thread alife
# i leave the cycle
break
else:
# if we tried all threads
# and there aren't any alife
# set flag for cycle leaving
is_any_thread_live = False
=====0.5 seconds after begining=====
first counter = 1
second counter = 0
=====1.0 seconds after begining=====
first counter = 2
second counter = 1
=====1.5 seconds after begining=====
first counter = 3
second counter = 1
=====2.0 seconds after begining=====
first counter = 4
second counter = 2
=====2.5 seconds after begining=====
first counter = 5
second counter = 2
=====3.0 seconds after begining=====
first counter = 5
second counter = 3
=====3.5 seconds after begining=====
first counter = 5
second counter = 3
=====4.0 seconds after begining=====
first counter = 5
second counter = 4
=====4.5 seconds after begining=====
first counter = 5
second counter = 4
=====5.0 seconds after begining=====
first counter = 5
second counter = 5