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

Staring 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, resspectively:
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

See also

The global interpreter lock makes sure that only one thread runds 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