Tech With Tim Logo
Go back

What is a Thread?

What is Multi-Threading

To understand multi-threading we must first understand what a thread and a process are. Processes are like programs running on your computer, they have their own allocated memory (in ram). A thread is something that belongs to a process. Multiple threads can belong to one process. Your computer has lots of processes running at the same time and it needs the CPU to process them as fast as possible. A modern day CPU has multiple cores that are capable of solving unique tasks at the same time (in parallel). The processes that are running on your computer will be divided among the multiple cores to increase efficiency. Since each process is divided among the cores that means that the threads belonging to each process will only be run on one core. So whats the advantage of creating multiple threads? Well each thread represents a task in your program and sometimes tasks don't need to be running or are in and IDLE state waiting for something to happen. Take for example connecting to a server, it may take a few seconds to connect to a server and in that time the code is simply waiting for that connection to be established. So the advantage of threads is that when one is not running another can be. So when one thread "hangs" or isn't executing any code then the other thread can take over and start performing tasks. The video explains this much more in depth.

Source Code

import threading
import time


class myThread (threading.Thread):
   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 + "\n")
      print_time(self.name, self.counter, 5)
      print ("Exiting " + self.name + "\n")


def print_time(threadName, delay, counter):
   while counter:
      time.sleep(delay)
      print ("%s: %s %s" % (threadName, time.ctime(time.time()), counter) + "\n")
      counter -= 1

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

# Start new Threads
thread1.start()
thread2.start()
thread1.join()
thread2.join()
print ("Exiting Main Thread")
Design & Development by Ibezio Logo