Operating Systems handle and provide mechanisms for multiprocessing. Developers can spawn new processes using the multiprocessing
package library in python.
Signature of Process class.
Process class takes the group, target, name, args and kwargs as parameters.
Process(group=None, target=None, name=None, args=(), kwargs={})
Here we’ll see how to to declare processes and execute it.
from multiprocessing import Process import os class Loop: def __init__(self, num): self.num = num self.loop = lambda n: [y for y in n] print(self.loop(self.num)) if __name__ == "__main__": [Process(target=Loop, args=(10,)) for x in range(0, 10)]
Output :
25200 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 25201 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 25202 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 25203 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 25204 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 25205 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 25206 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 25207 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 25208 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 25209 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Explanation:
A class Loop is defined. We create 10 processes. These processes are iteratively ( a typical for loop )created.
[Process(target=Loop, args(10,)) for x in rage(0, 10)]
A new process is created using the imported Process class with the passing the class name that has been defined to create an object in the process. Seconds parameter consists of parameters to be given to the class.
Process(target=Loop, args=(10,))
For lambda functions in the program visit :Lambda Operator in Python