Threads

Program threads are useful for asynchronous actions in a program. Suppose your program plays a sequence of sound samples and you want change the playback speed while it plays. You could of course check for user input regularly in-between playing samples, but this involves a lot of useless calls and it complicates and interrupts the flow of playing. A better solution would be to put the playing process into a thread and use a second thread that just waits for user input and passes it to the playing thread only when user input is coming in.

Example with two threads executing the same function:

import threading
import time


class myThread(threading.Thread):
  # constructor calls threading init
  def __init__(self,threadID,name,counter):
    threading.Thread.__init__(self)
    self.threadID = threadID
    self.name = name
    self.counter = counter
  def run(self):
    print("Starting " + self.name)
    while self.counter:
      print(self.name + " " + str(self.counter))
      time.sleep(0.5*self.counter)
      self.counter -= 1
    print(self.name + " ends")


# Create new threads
thread1 = myThread(1,"Thread-1",6)
thread2 = myThread(2,"Thread-2",5)

# Start new threads
thread1.start()
thread2.start()

# Wait for both threads to finish
thread1.join()
thread2.join()
print ("Main thread ends")


Example with two threads, both executing their own functions like e.g. a fast-running audio thread and a slow GUI thread:

import threading
import time


class myThread1(threading.Thread):
  # constructor calls threading init
  def __init__(self,threadID,name,counter):
    threading.Thread.__init__(self)
    self.threadID = threadID
    self.name = name
    self.counter = counter
  def run(self):
    print("Starting " + self.name)
    while self.counter:
      print(self.name + " " + str(self.counter))
      time.sleep(0.1)
      self.counter -= 1
    print(self.name + " ends")


class myThread2(threading.Thread):
  # constructor calls threading init
  def __init__(self,threadID,name,counter):
    threading.Thread.__init__(self)
    self.threadID = threadID
    self.name = name
    self.counter = counter
  def run(self):
    print("Starting " + self.name)
    while self.counter:
      print(self.name + " " + str(self.counter))
      time.sleep(1)
      self.counter -= 1
    print(self.name + " ends")



# Create new threads
thread1 = myThread1(1,"Audio",30)
thread2 = myThread2(2,"GUI",5)

# Start new threads
thread1.start()
thread2.start()

# Wait for both threads to finish
thread1.join()
thread2.join()
print ("Main thread ends")