[Tutor] Fwd: Concept of multithreading

Manprit Singh manpritsinghece at gmail.com
Mon Aug 23 07:44:29 EDT 2021


Dear Sir ,

Just need to know if the below written example can be taken as an
introduction level example of multithreading or not ?
import time
import threading

def sumoflist(seq):
    sum_no = 0
    for num in seq:
        sum_no += num
    time.sleep(6)
    print("Sum of list",sum_no)

def sumoftuple(seq):
    sum_no = 0
    for num in seq:
        sum_no += num
    time.sleep(3)
    print("Sum of tuple",sum_no)


sumoflist([1, 2, 3])
sumoftuple((2, 4, 3))

This is sequential execution , it takes around 9 seconds to complete, due
to a delay of 6 second in one function and 3 seconds delay in another
function . On the other hand if i take an another approach as given below :

t1 = threading.Thread(target=sumoflist, args=([1, 2, 3],))
t2 = threading.Thread(target=sumoftuple, args=((2, 4, 3),))
t1.start()
t2.start()
t1.join()
t2.join()

It takes around 6 seconds to complete the task, in this approach the
seconds subprocess executes when the CPU is idle during delay in the first
thread . This approach, according to me, can be a basic introduction to the
idea of multithreading . i need your comments .

Regards
Manprit Singh



---------- Forwarded message ---------
From: Manprit Singh <manpritsinghece at gmail.com>
Date: Sun, Aug 22, 2021 at 10:10 AM
Subject: Concept of multithreading
To: <tutor at python.org>


Dear sir,

As far as I have gone through the literature available, i got to know that
multithreading is used for concurrent subprocesses, Although they are not
truly concurrent (appears to be concurrent) - like if i have two
subprocesses, i can process them in a concurrent way using multithreading
module(An Example -in that way if CPU is idle for one subprocess, second
subprocess can take place at that time, This would same total execution
time).
For Example :
import time
import threading

def sumoflist(seq):
    sum_no = 0
    for num in seq:
        sum_no += num
    time.sleep(6)
    print("Sum of list",sum_no)

def sumoftuple(seq):
    sum_no = 0
    for num in seq:
        sum_no += num
    time.sleep(3)
    print("Sum of tuple",sum_no)

Calling these two functions in a sequential manner will take a total time
approx.  9 seconds, as delay of 6 second and 3 seconds is introduced in the
functions.

Now using threading module, with following code:

t1 = threading.Thread(target=sumoflist, args=([1, 2, 3],))
t2 = threading.Thread(target=sumoftuple, args=((2, 4, 3),))
t1.start()
t2.start()
t1.join()
t2.join()

It will take less time, because one of the thread may utilize the CPU idle
time of another thread .

Is my understanding correct ?

This can be treated as a very basic example of multithreading ?

Although the threading module is used for IO bound processes.

Regards
Manprit Singh


sumoflist([1, 2, 3])
sumoftuple((2, 4, 3))


More information about the Tutor mailing list