Python’s multiprocessing package allows the users to create new processes and access the Python API. If you’ve ever played around with the threading module, this is very comparable. Multiple task performance is necessary. We must import the multiprocessing module into the Python script to do multiprocessing operations. When two processes or threads attempt to access a shared resource such as memory files or other data, it might cause problems in the programming world. Thus, we need to secure that access using a lock. Sharing the main memory and accessories allow the processing units to run the programs simultaneously.
The multiprocessing application divides up into smaller units and operates separately. The operating system assigns a processor to each process. To prevent another process from running an equivalent function until the lock is released, we utilize the multiprocessing Lock class to obtain a lock on the process. The Lock class primarily accomplishes two functions. The acquire() method is used to first obtain a lock, while the release() function is used to release the lock.
import multiprocessing
def function(lock):
lock.acquire()
print("function ran.")
lock.release()
def function_run():
lock = multiprocessing.Lock()
P1 = multiprocessing.Process(target=function, args=(lock,))
P2 = multiprocessing.Process(target=function, args=(lock,))
P1.start()
P2.start()
P1.join()
P2.join()
if __name__ == "__main__":
function_run()
The output should look like this:
function ran.
function ran.
We can also use Pool class to manage the multiprocessing.
from multiprocessing import Pool
import time
COUNT = 500_000_000
def countdown(n):
while n > 0:
n -= 1
if __name__ == "__main__":
print("Running...")
start = time.time()
pool = Pool(processes=4)
pool.apply_async(countdown, [COUNT//4])
pool.apply_async(countdown, [COUNT//4])
pool.apply_async(countdown, [COUNT//4])
pool.apply_async(countdown, [COUNT//4])
pool.close()
pool.join()
end = time.time()
print("Done.")
print("Time taken in seconds - ", end - start)