Repository navigation
Threading
Thread is the smallest unit of execution in an operating system. It is not in 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.
To understand the functionality of threads in depth, we need to learn about the lifecycle of the threads or the different thread states. Typically, a thread can exist in five distinct states. The different states are shown below:
- New Thread: A new thread begins its life cycle in the new state. However, at this stage, it has not yet started and it has not been allocated any resources. We can say that it is just an instance of an object.
- Runnable: As the newly born thread is started, the thread becomes runnable i.e. waiting to run. In this state, it has all the resources but still task scheduler have not scheduled it to run.
- Running: In this state, the thread makes progress and executes the task, which has been chosen by task scheduler to run. Now, the thread can go to either the dead state or the non-runnable/ waiting state.
- Non-running/waiting: In this state, the thread is paused because it is either waiting for the response of some I/O request or waiting for the completion of the execution of other thread.
- Dead: A runnable thread enters the terminated state when it completes its task or otherwise terminates.
The following diagram shows the complete life cycle of a thread:

In this section, we will see the different types of thread. The types are described below:
These are user-managed threads. In this case, the thread management kernel is not aware of the existence of threads. The thread library contains code for creating and destroying threads, for passing message and data between threads, for scheduling thread execution and for saving and restoring thread contexts. The application starts with a single thread.
- Thread switching does not require Kernel mode privileges.
- User level thread can run on any operating system.
- Scheduling can be application specific in the user level thread.
- User level threads are fast to create and manage.
- In a typical operating system, most system calls are blocking.
- Multithreaded application cannot take advantage of multiprocessing.
Operating System managed threads act on kernel, which is an operating system core. In this case, the Kernel does thread management. There is no thread management code in the application area. Kernel threads are supported directly by the operating system. Any application can be programmed to be multithreaded. All of the threads within an application are supported within a single process.
The Kernel maintains context information for the process as a whole and for individual threads within the process. Scheduling by the Kernel is done on a thread basis. The Kernel performs thread creation, scheduling and management in Kernel space. Kernel threads are generally slower to create and manage than the user threads. The examples of kernel level threads are Windows, Solaris.
- Kernel can simultaneously schedule multiple threads from the same process on multiple processes.
- If one thread in a process is blocked, the Kernel can schedule another thread of the same process.
- Kernel routines themselves can be multithreaded.
- Kernel threads are generally slower to create and manage than the user threads.
- Transfer of control from one thread to another within the same process requires a mode switch to the Kernel.
In multithreading, process and thread are two very closely related terms having the same goal to make computer able to do more than one thing at a time. A process can contain one or more threads but on the contrary, thread cannot contain a process. However, they both remain the two basic units of execution. A program, executing a series of instructions, initiates process and thread both. The following table shows the comparison between process and thread:
| Process | Thread | |
|---|---|---|
| 1 | Process is heavy weight or resource intensive. | Thread is lightweight which takes fewer resources than a process. |
| 2 | Process switching needs interaction with operating system. | Thread switching does not need to interact with operating system. |
| 3 | In multiple processing environments, each process executes the same code but has its own memory and file resources. | All threads can share same set of open files, child processes. |
| 4 | If one process is blocked, then no other process can execute until the first process is unblocked. | While one thread is blocked and waiting, a second thread in the same task can run. |
| 5 | Multiple processes without using threads use more resources. | Multiple threaded processes use fewer resources. |
| 6 | In multiple processes, each process operates independently of the others. | One thread can read, write or change another thread's data. |
| 7 | If there would be any change in the parent process then it does not affect the child processes. | If there would be any change in the main thread then it may affect the behavior of other threads of that process. |
| 8 | To communicate with sibling processes, processes must use inter-process communication. | Threads can directly communicate with other threads of that process. |
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.
-
Speed of communication: Multithreading improves the speed of computation because each core or processor handles separate threads concurrently.
-
Program remains responsive: It allows a program to remain responsive because one thread waits for the input and another runs a GUI at the same time.
-
Access to global variables: In multithreading, all the threads of a particular process can access the global variables and if there is any change in global variable then it is visible to other threads too.
-
Utilization of resources: Running of several threads in each program makes better use of CPU and the idle time of CPU becomes less.
-
Sharing of data: There is no requirement of extra space for each thread because threads within a program can share same data.
-
Not suitable for single processor system: Multithreading finds it difficult to achieve performance in terms of speed of computation on single processor system as compared with the performance on multi-processor system.
-
Issue of security: As we know that all the threads within a program share same data, hence there is always an issue of security because any unknown thread can change the data.
-
Increase in complexity: Multithreading can increase the complexity of the program and debugging becomes difficult.
-
Lead to deadlock state: Multithreading can lead the program to potential risk of attaining the deadlock state.
-
Synchronization required: Synchronization is required to avoid mutual exclusion. This leads to more memory and CPU utilization.
Running several threads is similar to running several different programs concurrently, but with the following benefits:
- Multiple threads within a process share the same data space with the main thread and can therefore share information or communicate with each other more easily than if they were separate processes.
- Threads are sometimes called light-weight processes and they do not require much memory overhead; they are cheaper than processes.
A thread has a beginning, an execution sequence, and a conclusion. It has an instruction pointer that keeps track of where within its context is it currently running.
- It can be pre-empted (interrupted).
- It can temporarily be put on hold (also known as sleeping) while other threads are running (this is called yielding).
There are two different kind of threads:
- kernel thread
- user thread
Kernel Threads are a part of the operating system, while the User-space threads are not implemented in the kernel.
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.
The threading module exposes all the methods of other modules and provides some additional methods:
-
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 to the methods, 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.
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
In terms of computing, daemon is a background process that handles the requests for various services such as data sending, file transfers, etc. Following is the implementation of daemon threads in python.
Example:
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()