Search notes:

Python standard library: threading

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)
Github repository about-python, path: /standard-library/threading/demo.py

Starting a thread and waiting for its termination

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()
Github repository about-python, path: /standard-library/threading/start-join.py

daemon

A thread has a (boolean) daemon property.
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.
Demonstration program:
import sys
import threading
import time


def work():
    time.sleep(10)
    print('Finished')


daemon = sys.argv[1].lower() == 'true' if len(sys.argv) > 1 else True

thread = threading.Thread(target=work)
thread.daemon = daemon
thread.start()

print(f'Main finished; daemon={daemon}')
Execute with
python3 /tmp/x.py true
python3 /tmp/x.py false

See also

threading.Lock
The global interpreter lock makes sure that only one thread runs in the Python virtual machine.
sys.setswitchinterval() determines how frequently Python's virtual machine switches between threads.
The Python tutorial recommends to use the queue module for inter-thread communication and coordination.
standard library

Index