Blocking and non-blocking threads in python - Simplified














































Blocking and non-blocking threads in python - Simplified



Blocking and non-blocking threads in python - Simplified


What is a non blocking thread?
In computer science, an algorithm is called non-blocking if failure or suspension of any thread cannot cause failure or suspension of another thread; for some operations, these algorithms provide a useful alternative to traditional blocking implementations.
So in layman's term,
A thread is non-blocking when it doesn't cause other threads to wait until the other thread(s) are finished.

What is a blocking thread?
In contrast a blocking thread is the thread that will wait before some other thread or threads have finished their execution.

Real life examples exist for both the types of thread processes in computing.

In this tutorial we will simulate both these type of threads.

Major use of threading is to have a thread that is infact non-blocking so that we could do more with lesser time if both of the threads don't necessarily "connect" or are dependent on each other.

Code for non-blocking thread (with comments) :

# importing libraries
import random
import time
from threading import Thread

# target function which takes a time at random(from 0 to 2 seconds) to simulate some "work"
def worker(instance):
    time_taken = random.uniform(0, 2)
    time.sleep(time_taken)
    print('thread %s : completed in %s sec' % (instance, time_taken))


if __name__ == '__main__':
    for i in range(0, 10):
        # don't confuse with the variable "t" it is not bound to any thread! it is just a name
        t = Thread(target=worker, args=(i,))
        # starting the thread which will continue working in background after this.
        t.start()
Output:



Explanation:

Hope you have read the comments.
So what the code does is that it starts 10 threads named thread 0,thread 1 and so on on a worker() which simulates some work using time.sleep() with random time.

when a thread completes we can see that it outputs the time in which it got completed.

We can see from the output that the threads may have started sequentially but they don't get completed sequentially like thread 5 got completed before thread 0.

If we make a small modification and add some code to the main program outside of thread then we can see how it works and no thread is dependent on neither the other threads or  the main program.


Code:

# importing libraries
import random
import time
from threading import Thread

# target function which takes a time at random(from 0 to 2 seconds) to simulate some "work"
def worker(instance):
    time_taken = random.uniform(0, 2)
    time.sleep(time_taken)
    print('thread %s : completed in %s sec' % (instance, time_taken))


if __name__ == '__main__':
    for i in range(0, 10):
        # don't confuse with the variable "t" it is not bound to any thread! it is just a name
        t = Thread(target=worker, args=(i,))
        # starting the thread which will continue working in background after this.
        t.start()
        # this just simulates a main program that does some work which takes 2 seconds of time
        time.sleep(1)
        print("Hi,there.Main program here!")
Output : 



Explanation :
 Similar to the other program the only difference is a main program included that works independent of the threads.



A blocking thread in contrast to the above examples will wait for other threads to finish their execution.
Although we wouldn't require using such threads as usually the purpose of a thread is parallelism and concurrency which blocking threads don't do. 

code:
# importing libraries
import random
import time
from threading import Thread

# target function which takes a time at random(from 0 to 2 seconds) to simulate some "work"
def worker(instance):
    time_taken = random.uniform(0, 2)
    time.sleep(time_taken)
    print('thread %s : completed in %s sec' % (instance, time_taken))

if __name__ == '__main__':

    # this just simulates a main program that does some work which takes 2 seconds of time
    for i in range(0, 10):
        # don't confuse with the variable "t" it is not bound to any thread! it is just a name
        t = Thread(target=worker, args=(i,))
        # starting the thread which will continue working in background after this.
        t.start()
        t.join() #the only change in the code to make it a blocking thread!!!


Output:




Explanation:

The only modification in the code we did is t.join() what this does is that it will wait or the previous thread to complete its execution before starting up and same way other threads would  work.


More Articles of Mohta Rahul Suresh:

Name Views Likes
How to kill a thread in python - part 1 875 0
IMAGE PROCESSING FROM SCRATCH USIGN PIL AND OPENCV SERIES : PART 3 538 0
Automated testing and implementing unit testing using python 896 0
Searching algorithms in RUST Part 1 686 0
Check validity of Email address using SMTP and dnspython library. 3940 0
Blocking and non-blocking threads in python - Simplified 6700 0
IMAGE PROCESSING FROM SCRATCH USIGN PIL AND OPENCV SERIES : PART 7 492 0
How to run C and C++ on Google Colab. 46722 1
Create a telegram bot to get notifications about price of your favourite Cryptocurrency (using Python) 2188 1
Image processing from Scratch usign PIL and OpenCV Series : Part 1 393 0
Searching Algorithms in RUST part 2 317 0
Make a QR-code with your Face on it. 2110 0
RUST CHEATSHEET Part 2 452 0
How to kill a thread in python - part 2 672 0
Hiding an Image inside another Image - Steganography using python. 3222 0
RUST CHEAT SHEET part 1 569 0
PyPy installation, usage and speed comparison with CPython 753 0
IMAGE PROCESSING FROM SCRATCH USIGN PIL AND OPENCV SERIES : PART 6 281 0
Convert text in an image to an audio file using tesseract and gTTS in python. 1825 0
IMAGE PROCESSING FROM SCRATCH USIGN PIL AND OPENCV SERIES : PART 5 344 0
IMAGE PROCESSING FROM SCRATCH USIGN PIL AND OPENCV SERIES : PART 4 305 0
Convert a CSV file to a table in a markdown file 4141 0
pandasgui tutorial 1074 3
IMAGE PROCESSING FROM SCRATCH USIGN PIL AND OPENCV SERIES : PART 2 396 0
Algorithmic trading basics with google stocks using python. 858 0

Comments