Python

Exploring Threading module of python

In my last article in python series, We have learned about the Database connection for SQLite of python. If you have not checked the articles of python series then I would be recommended to please check all the articles posted in python category. From the<a ” href=”http://mobologicplus.com/category/python/”> Python category, you can learn all basic and fundamental concept of python. Now the motivation is the same in this article to utilize our awesome day into learning space.

In this python series, we will try to learn about the python threading concert. As we know a thread is playing a very important role in software engineering. But unfortunately, we did not utilize most of the treading concept in our project life. It might be the reason for fear the thread unpredictable behaviors. Most developers like us, we are used 2% of thread concept in any project life. But again in the software industry, the thread is playing an important role in executing any task. It always takes less time in execution in any process because we can distribute the work between the multiple threads easily.

In software Engineering generally,  two kinds of thread are available.

  1. Kernal thread or main thread
  2. User thread

Python Thread Module:

There are two modules which support the usage of threads in Python:

  • thread module and
  • threading module

As we know that everyone has their own legacy to use the python version. Few people are using the version which is less than 3 .0 and some people used the current version or greater 3.0 version. In the python version, 3.0 is depreciated by the Python team and introduced the threading concept which is based on the object-oriented thread concept.

As we know the world is currently sifted on Object-Oriented concept. So the module “thread” treats a thread as a function, while the module “threading” is implemented in an object-oriented way, i.e. every thread corresponds to an object.  So in this python thread concept, we will learn about the threading concept rather than thread concept.

Threading module:

To create user-defined thread class, inherit from “threading. Thread”. Override __init__() and run() methods
Once ‘start()’ is called, “run()” will get triggered as a thread. Threading module provides methods for creating a thread, getting status on threads and creating synchronization objects.

Methods:

active_count(): Number for active threads

current_thread(): Current running thread id

enumerate(): list of alive thread objects

Condition(): create condition sync object

Event(): create event sync object

Lock(): create lock object

RLock(): create recursive lock object

Semaphore(): Create a semaphore object

BoundedSemaphore(): semaphore with bounded upper limit

Synchronization methods:

Lock/RLock: Acquire and release lock

Condition: conditional wait to wake up

Semaphore: Count based acquire/release 

Event: Signal bases sync

Now the question is what is the Thread Object, Lock Thread Object, Condition Thread Object, Semaphore thread object or Event Object. We will go into the detail of the mentioned Object.

Why I am calling Object every time rather than thread. As we already pointed on the beginning of articles,  thread in python version 3.0 treaded like Object.

Thread Object:

Define thread class and create a new instance of thread class. Let’s see what are methods available in the thread object.

start(): Starts thread’s activity

run(): method that actually run as a thread

join(): wait until the thread terminates

isalive(): whether thread is alive or not

Lock/RLock Object:

Locking based on binary value. (0 or 1). Let’s see what are methods available in the Lock/Rlock object.

acquire([blocking]): acquire a lock, blocking or non-blocking

release(): release an acquired lock. Lock can be acquired by any waiting thread

Conditional Object:

Provide conditional release of lock and wait. Let’s see what are methods available in the Conditional object.

acquire(): acquire the lock

release(): release the lock

wait([timeout]): wait till get notification. Temp release the lock

notify(n=1): notify ’n’ threads in wait state, and they will reacquire lock

notifyall(): wake up all the waiting threads. 

Semaphore/BoundedSemaphore Object:

It is count-based locking.

acquire(): acquire a lock, and reduce count by 1.

release(): release a lock

Event objects:

It is a mechanism based on True/False flag.

is_set(): whether flag is set or not

set(): set the flag status as true. If true no threads will go in wait state

clear(): unset the flag. 

wait(): block until the flag is set True

Let’s see by an example of all to understand clearly.

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
      #enable for lock sync
      #threadLock.acquire()
      print_time(self.name, self.counter, 5)
      print "Exiting " + self.name
      #enable for lock sync
      #threadLock.release()

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


#enable for Lock sync
#threadLock = threading.Lock()

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

As in the above example, we have played acquiring the lock and releasing the lock of an object. As we know the concept of synchronization once the thread holds the object then other thread cannot access until the thread releases the lock. I hope this illustration will help you to understand the multiple thread concept.

Summary:

Now we have a good understanding of the Threading module. We have seen methods and a few examples to play around it. If you still having issue or doubts then please add a comment I will try to reply as much possible. In my next python tutorial series, we will learn about the read and write data from XML with examples.

If you are wondering to learn Android then Please Learn from Android category and wondering to lean Kotlin then Kotlin Category will help you. If you want to learn all the python article, then learn from the python category.

Please do subscribe your email to get the newsletter on this blog on below and if you like this post then do not forget to share like and comment on the below section.

Happy Coding

0 0 votes
Article Rating
Exploring Threading module of python

Recent Posts

Hide your production API key or any sensitive data in Android

Hi everyone, In this article, we are going to learn how to hide the production… Read More

2 years ago

How to handle the localisation or multi language support in android with examples?

Hello everyone, Today in this article, we are going to learn about localisation to support… Read More

2 years ago

How to convert any callback to Coroutines and use them in Kotlin Android?

Hello everyone, In this article, we are going to learn something to handle the callback… Read More

2 years ago

Request Permission Launcher with Kotlin in Android

In this article, we are learning about the run time permissions for request permission launchers.… Read More

2 years ago

Implement the SMS User Consent API and SMS Retriever API in Android

Hello everyone. In my last tutorial, we learned about the Jetpack Compose introduction and about applying the… Read More

3 years ago

Jetpack Compose Coroutine flow with LiveData/ViewModel in Android

Hello everyone, In this article, we are going to learn about the Jetpack Compose with… Read More

3 years ago