Skip to content

Threading

Farrokh Karimi edited this page Aug 26, 2018 · 10 revisions

Home Page
Previous Page

Thread

Thread is the smallest unit of execution in an operating system. It is not on itself a program but runs within a program. In other words, threads are not independent of one other and share code section, data section, etc. with other threads. These threads are also known as lightweight processes.

States of Thread

  1. New Thread
  2. Runnable
  3. Running
  4. Waiting
  5. Dead

Types of Thread

  1. User Level Threads
  2. Kernel Level Threads

Threading

There are several modules which support the usage of threads in Python. The best module is threading. The newer threading module provides much more powerful, high-level support for threads than the other modules. Also the threading module exposes all the methods of other modules and provides some additional methods. Here is some useful methods of threading module:

  • threading.activeCount(): Returns the number of thread objects that are active.
  • threading.currentThread(): Returns the number of thread objects in the caller's thread control.
  • threading.enumerate(): Returns a list of all thread objects that are currently active.

In addition, the threading module has the Thread class that implements threading. The methods provided by the Thread class are as follows:

  • run(): The run() method is the entry point for a thread.
  • start(): The start() method starts a thread by calling the run method.
  • join([time]): The join() waits for threads to terminate.
  • isAlive(): The isAlive() method checks whether a thread is still executing.
  • getName(): The getName() method returns the name of a thread.
  • setName(): The setName() method sets the name of a thread.

Create Thread

To implement a new thread using the threading module, you have to do the following:

  • Define a new subclass of the Thread class.
  • Override the __init__(self [,args]) method to add additional arguments.
  • Then, override the run(self [,args]) method to implement what the thread should do when started. Once you have created the new Thread subclass, you can create an instance of it and then start a new thread by invoking the start(), which in turn calls the run() method.

Eample 1:

#!/usr/bin/python3

import threading
import time

exitFlag = 0

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)
      print_time(self.name, self.counter, 5)
      print ("Exiting " + self.name)

def print_time(threadName, delay, counter):
   while counter:
      if exitFlag:
         threadName.exit()
      time.sleep(delay)
      print ("%s: %s" % (threadName, time.ctime(time.time())))
      counter -= 1

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

# Start new Threads
thread1.start()
thread2.start()
thread1.join()
thread2.join()
print ("Exiting Main Thread")

Output:

Starting Thread-1
Starting Thread-2
Thread-1: Sun Aug 12 22:48:12 2018
Thread-2: Sun Aug 12 22:48:13 2018
Thread-1: Sun Aug 12 22:48:13 2018
Thread-1: Sun Aug 12 22:48:14 2018
Thread-2: Sun Aug 12 22:48:15 2018
Thread-1: Sun Aug 12 22:48:15 2018
Thread-1: Sun Aug 12 22:48:16 2018
Exiting Thread-1
Thread-2: Sun Aug 12 22:48:17 2018
Thread-2: Sun Aug 12 22:48:19 2018
Thread-2: Sun Aug 12 22:48:21 2018
Exiting Thread-2
Exiting Main Thread

Example 2:

#!/usr/bin/python3

import threading
import time
import random
def Thread_execution(i):
   print("Execution of Thread {} started".format(i))
   sleepTime = random.randint(1,4)
   time.sleep(sleepTime)
   print("Execution of Thread {} finished".format(i))
for i in range(4):
   thread = threading.Thread(target=Thread_execution, args=(i,))
   thread.start()

Output:

Execution of Thread 0 started
Execution of Thread 1 started
Execution of Thread 2 started
Execution of Thread 3 started
Execution of Thread 1 finished
Execution of Thread 2 finished
Execution of Thread 0 finished
Execution of Thread 3 finished

Daemon threads

In terms of computing, daemon is a background process that handles the requests for various services such as data sending, file transfers, etc.

Example:

#!/usr/bin/python3

import threading
import time

def daemonThread():
    for i in range (20):
        print("This is a daemon thread")
        time.sleep(1)
        
if __name__ == '__main__':
    daemonThread = threading.Thread(target = daemonThread)
    daemonThread.setDaemon(True)
    daemonThread.start()

Multithreading

As we have discussed earlier that Multithreading is the ability of a CPU to manage the use of operating system by executing multiple threads concurrently. The main idea of multithreading is to achieve parallelism by dividing a process into multiple threads. In a more simple way, we can say that multithreading is the way of achieving multitasking by using the concept of threads.

Next Page

Clone this wiki locally