What is Multiprocessing?
Multiprocessing refers to the ability of a system to support more than one processor at the same time. Applications in a multiprocessing system are broken into smaller routines that run independently. The operating system allocates these threads to the processors improving system performance.
A multiprocessing system can have:
- multiprocessor, i.e. a computer with more than one central processor.
- multi-core processor, i.e. a single computing component with two or more independent actual processing units (called “cores”)
To import the multiprocessing module, we do:
import multiprocessingExample: 1
import multiprocessing
def test():
print("this is my multiprocessing prog")
if __name__ == '__main__':
m = multiprocessing.Process(target=test)
print("this is my main prog")
m.start()
m.join()
OUTPUT:
Example: 2
Calculate the square of the given number using multiprocessing
def square(n):
return n**2
if __name__ == '__main__':
with multiprocessing.Pool(processes=4) as pool :
out = pool.map(square , [1,2,3,4,5,6,7,8,9])
print(out)
OUTPUT:
Example: 3
import multiprocessing
def sender(conn , msg) :
for i in msg:
conn.send(i)
conn.close()
def receive(conn) :
while True :
try :
msg = conn.recv()
except Exception as e :
print(e)
break
print(msg)
if __name__ == '__main__' :
msg = ["my name is sudh", "this is my msg to students", "I am taking class for multiprocessing " ]
parent_con , child_con = multiprocessing.Pipe()
m1 = multiprocessing.Process(target=sender , args = (child_con , msg))
m2 = multiprocessing.Process(target=receive , args =(parent_con,))
m1.start()
m2.start()
m1.join()
child_con.close()
m2.join()
parent_con.close()
OUTPUT:
No comments:
Post a Comment