import threading, time
def thread_func(name, val):
for i in range(val):
print(name + ": i = " + str(i))
for i in range(5):
thread = threading.Thread(target = thread_func, args=('Thread ' + str(i), 5-i))
thread.start()
time.sleep(1)
When deriving a class from threading.Thread, it has the two methods start() and join that start a thread and wait for its completion, respectively:
import time
import threading
class T(threading.Thread):
def __init__(self, id, dur, n):
self.id = id
self.dur = dur
self.n = n
super().__init__()
def run(self):
for i in range(self.n):
time.sleep(self.dur)
print(f'{self.id}: {i} of {self.n}')
threads = (
T('foo', 0.5, 5),
T('bar', 0.6, 4),
T('baz', 0.7, 3)
)
for t in threads:
t.start()
for t in threads:
t.join()
Setting this property to True marks the thread as a daemon thread. Daemon threads are intended to run in the background while non-daemon threads are active.
The process exits as soon as no non-daemon threads remain. Consequently, daemon threads may not have an opportunity to clean up their resources.
The main (initial) thread does not have this property set.