[Tutor] Multi threading and I/O bound process

Manprit Singh manpritsinghece at gmail.com
Sun Nov 28 20:53:17 EST 2021


Dear sir,

Just need to know if the below example is a correct example of
multithreading used with I/O bound process :

1) Without multi threading

import time
import urllib.request
# a function to dsplay first 25 bytes of a webpage
def readpage(urladd):
    with urllib.request.urlopen(urladd) as fobj:
        print(fobj.read(25))

t0 = time.time()
for _ in range(6):
    readpage("https://www.xyz.com/")
t1 = time.time()
print(t1-t0)
will display the first 25 bytes of the webpage  6 times in a sequential
order. and measure the time

2) Multithreading Using constructor   :

t0= time.time()
import threading
threadsgrp = []
for _ in range(6):
    thread = threading.Thread(target=readpage,args=("https://www.xyz.com/
",))
    threadsgrp.append(thread)
    thread.start()
for th in threadsgrp:
    th.join()
t1 =time.time()
print(t1-t0)

3)  Multithreading using subclass :

t1 = time.time()
class Techlivethread(threading.Thread):
    def __init__(self, add):
        threading.Thread.__init__(self)
        self.add = add
    def run(self):
        readpage(self.add)

grp =[]
for _ in range(6):
    th1 = Techlivethread("https://www.xyz.com/")
    grp.append(th1)
    th1.start()
for ele in grp:
    ele.join()
t2 = time.time()
print(t2-t1)

Kindly comment


More information about the Tutor mailing list