[Tutor] Concept of multithreading
Manprit Singh
manpritsinghece at gmail.com
Sun Aug 22 00:40:05 EDT 2021
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