Skip to content

Commit 6869f4a

Browse files
committed
Added multi-theading notes
1 parent 2ed7868 commit 6869f4a

File tree

3 files changed

+173
-1
lines changed

3 files changed

+173
-1
lines changed

16. File Handling.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@
6969

7070

7171
print("Instead of explicitelty, writing out f.close() at last, to free up the res., we can use 'with' statemne, that woudl automtically, closes the file,after execution of the bloc is completed")
72-
with open("kumar.txt",'w') as f2:
72+
with open("C:/Users/HP/Downloads/College/kumar.txt",'w') as f2:
7373
print("I am going to copy, all contents of vishal.txt to kumar.txt",f2.write(f.read()))
7474
print("Do the kumar is closed within the block?",f2.writable())
7575

17. Multi-threading.py

+172
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,172 @@
1+
from threading import *
2+
import time
3+
print("Multi-tasking: Executing different tasks simultaneously. 2 types: \n 1) Process-based Multi-tasking: Multiple tasks execute simultaneously, where each task is an independent process with it's own memory space. Process-based multi-tasking is the most used concept, at the operating system level. \n 2) Thread-based Multi-tasking: Multiple tasks execute simultaneously, where each task is an independent part of the same program, and share the same memory space. Thread-based multi-tasking is the most used concept, at the application level.\n A thread is an: \n 1) Independent part of a program \n 2) It is considered as a flow of execution. \n 3) It is a python object \n FOr every thread, independent job is available. Whrever indedependednt jobs are available, multi-threading is best suited,as it provides better performance.\n in generally, every web server contains 60 threads. So, at a time, 60 client requests can be handled by the server simultaneodsuly. But,it can be icnreasesd/decreased, abed on our demand. After client requests completed, thread will be allocated to the next request \n. By default PVM, contains a single thread running, which is the main thread. We can sue threading library to do threading operations. For every thread, PVM assigns a unique identification no")
4+
5+
print("Current running thread Name",current_thread().name)
6+
7+
print("There are 3 ways to create a thread: \n 1) Create a thread without using any class. \n 2) Create a thread extending the Thread class. \n 3) Create a thread, without extending the Thread Class.\n")
8+
9+
print("1) Without extending any class: (Functional Programming Way)")
10+
def display():
11+
for _ in range(10):
12+
print("I'm a child thread: ",{current_thread().name})
13+
14+
t = Thread(target = display)
15+
list_of_threads = enumerate()
16+
print("\nList of active threads by default: ")
17+
for thread in list_of_threads:
18+
print(f"Thread Name: {thread.name}, Thread ID: {thread.ident}")
19+
print("\n")
20+
21+
print("Main thread will create the child thread, after start().Now, well have 2 threads, and both will execute simulataneously")
22+
t.start()
23+
list_of_threads = enumerate()
24+
print("\nList of active threads after i create another thread for our display function: ")
25+
for thread in list_of_threads:
26+
print(f"Thread Name: {thread.name}, Thread ID: {thread.ident}")
27+
print("\n")
28+
29+
30+
31+
32+
for _ in range(10):
33+
print("I'm a parent thread: ",{current_thread().name})
34+
35+
print("here, this parent thread printing statemtn is executed by the main thread, adn dsiplay() is executed by the chidl thread. Both threads execute simultaenously, we cant't predict the exact order in which they will print, but it is of no issue, since we only use multithreading fro 2 processes wehihc are independent, i.e their order of in between executions dont matter, since we wont care about the task, only about hte job being done. ID bth processes are dependent in case,then order is impo., over there, then we won;t use multithreading over there\n")
36+
37+
38+
print("2) Extending the Thread class: (OOPs Way)")
39+
40+
class child(Thread):
41+
def run(self):
42+
for _ in range(10):
43+
print("CHILD THREAD STATEMENT: I'm a child thread:",current_thread().name)
44+
45+
46+
list_of_threads = enumerate()
47+
print("\nList of active threads now: ")
48+
for thread in list_of_threads:
49+
print(f"Thread Name: {thread.name}, Thread ID: {thread.ident}")
50+
print("\n")
51+
52+
53+
t = child()
54+
print("Current thread is: ",current_thread().name)
55+
print("Im starting child thread...")
56+
t.start()
57+
58+
list_of_threads = enumerate()
59+
print("\nList of active threads after creating child thread instance: Note: this code is executed by the thread: ",current_thread().name)
60+
for thread in list_of_threads:
61+
print(f"LIST OF THREADS STATEMENT: Thread Name: {thread.name}, Thread ID: {thread.ident}")
62+
print("\n")
63+
64+
for _ in range(10):
65+
print("MAIN THREAD STATEMENT: I'm a parent thread: ",{current_thread().name})
66+
67+
68+
print("here, u can see hwo chidl thread and parent thread statemtns overlap during printing, since they are executing simultaneosuly. First, the child thread statemtns are overlapping with the main thread's list of thread print statements during simultaenoues execution,then after list of threads task completion, it overlaps with the main thread's parent thread printing statement task, thus runnign simultaenously.To make sure, a thread waits till the completion of another thread,to avoid overlapping like this, we need to use.join() method. We'll use that method in the enxt e.g.,\n")
69+
70+
print("3) Using Class, without extending the Thread class: (OOPs Way)")
71+
72+
list_of_threads = enumerate()
73+
print("\nList of active threads now: ")
74+
for thread in list_of_threads:
75+
print(f"LIST OF THREADS STATEMENT:Thread Name: {thread.name}, Thread ID: {thread.ident}")
76+
print("\n")
77+
78+
class square:
79+
def sq(self,li):
80+
time.sleep(5)
81+
for i in li:
82+
print(f"Square of {i} is {i*i} by {current_thread().name}")
83+
84+
class multiply:
85+
def mul(self,li):
86+
time.sleep(5)
87+
for i in li:
88+
print(f"Multiplied by 2 of {i} is {i*2} by {current_thread().name}")
89+
90+
li = [1,2,3,4,5]
91+
s = square()
92+
m = multiply()
93+
print("To give arguments to our thread object, as sq and mul function req., li to execute, we'll need another argument called args in the Thread object creation. ")
94+
child_thread_1 = Thread(target = s.sq, name = "child_thread_1", args = (li,))
95+
child_thread_2 = Thread(target = m.mul, name = "child_thread_2", args = (li,))
96+
97+
98+
print("Setting/modifying the thread names using ref_var.name = '' or ref_var.setName(''): Thread-3 = Square, Thread-4: Multiply")
99+
child_thread_1.name = "Square"
100+
child_thread_2.name = "Multiply"
101+
102+
print("WE can find no of active threads using active_count, if i print this statement, after starting both child threads, it will print in between them. But i want it to print no of active count of threads immeddiately after starting child 1 and 2 at the start,after starign, not in between print statemetns. To achieve, that as we know, this print statemnt is beigne xecuted y the main thread, and not by the child threads, so afters starting the child threads,ill make them sleep,so that since both child threads are sleeoping,they won;t be able to print anything,so our main thread woudl print this staemten first")
103+
104+
print("Starting 2 child threads.....")
105+
child_thread_1.start()
106+
child_thread_2.start()
107+
print("No of active threads = ",active_count(),"Executed by",current_thread().name)
108+
print("Check whether a thread is alive or not using is_alive() method: ")
109+
print("Do child-1 thread is alive now?",child_thread_1.is_alive())
110+
print("Do child-2 thread is alive now?",child_thread_2.is_alive())
111+
list_of_threads = enumerate()
112+
for thread in list_of_threads:
113+
print(f"LIST OF THREADS STATEMENT BEFORE JOIN: Thread Name: {thread.name}, Thread ID: {thread.ident}")
114+
print("\n")
115+
print("Now, I need to print this list of threads statement again, but only after complete exxecution of boht of the chidl threads, to know he active threads at last after execution completion of mul., and square., To do that, the main thread should wait till both child threads are completed. Then, only it should executes it's task. This will make sure LIST OF THREADS STATEMENT's will execute at last, after dispalyinf sqaure and multiplication, not in between overlapping displays like the previous eg.'s. To do that, we;ll use join(). It will make main thread to wait till both child threads complete")
116+
117+
118+
child_thread_1.join()
119+
child_thread_2.join()
120+
121+
122+
list_of_threads = enumerate()
123+
print("\nList of active threads now, after main thread waiting for child thread 1 and 2 to complete: ")
124+
for thread in list_of_threads:
125+
print(f"LIST OF THREADS STATEMENT ATLAST AFTER JOIN:Thread Name: {thread.name}, Thread ID: {thread.ident}")
126+
print("Do child-1 thread is alive now?",child_thread_1.is_alive())
127+
print("Do child-2 thread is alive now?",child_thread_2.is_alive())
128+
129+
print("\n")
130+
print("U might think if we use join() for all the threads, to wait unitl compeltion of another thread, it becomes like a sequential flow, then better go with single thread i.e noraml process execution, but even those cases, multi-threading may be ebneficail, let us see a e.g, case scenario of it")
131+
132+
133+
def venue():
134+
print("Searching for best venue....")
135+
time.sleep(5)
136+
global venue
137+
venue = "Leela Palace"
138+
print("Ater long discussions venue is finalised as, ",venue)
139+
140+
def invitation_printing():
141+
global color
142+
global size
143+
global design
144+
global other_details
145+
print("Here, even though i can print the invitaions, only after finalising the venue, ther is no neeed to wait compeltetly till they decide the place. Let, me deciede teh color,shape,design and fill alld etaisl in teh invitaiton,leaving space ot venu, after venu gets decided,then ill print the invitations.THus, multi-threading is useful here. If i use signle-threading, I would be waiting till venu is finalsied, even fro decidiing teh design of the invitaiton")
146+
color = "Blue"
147+
size = "16x16"
148+
design = "Box-Shaped"
149+
other_details = "Bride Name: X, Groom Name: Y"
150+
final_venue.join()
151+
print(f"Invitation: \n {other_details} \n Venue: {venue}")
152+
153+
154+
def marriage_arrangements():
155+
print("here,unlike invitation waiting forever for venue finalsiation, to print, we'll not wait forever, for invitation to complete to marraige. We'll do all other works, and wait for a speciif amt., of time. If invitation not gets pritned even after comepteing otehr thigns and waiting for a certain amt fo time, directly marriage will be done.")
156+
157+
print("Decorations work chosen...")
158+
print("List of relatives invitations needs to be sent gets decided.....")
159+
print("All other catering arranagements are beign planned....")
160+
print("All other marraige works completed, Ill wait till some more time. IF still i dint get invitaiton, marraige will be done straightly")
161+
invitation.join(10)
162+
print("Marriage completed successfully")
163+
164+
165+
final_venue = Thread(target = venue)
166+
invitation = Thread(target = invitation_printing)
167+
marriage = Thread(target = marriage_arrangements)
168+
169+
final_venue.start()
170+
invitation.start()
171+
marriage.start()
172+
print("here, eventhough the sequentail order is : Venue infalsiation -> Invitaiton printing - > Marriage, since we used multi-threading instead of single threading, we completed all other independednt works of each tasks simultaneously, and each thread, waited only in their crucial dependedncy part, whcih depends on the prev ., sequentail order task for execution, making the overall process faster.")

kumar.txt

Whitespace-only changes.

0 commit comments

Comments
 (0)