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")