Processes In Python

104 6

    Processes

    • When a user begins an application such as a Web browser, the application becomes a running process in the operating system. Before execution, a program simply resides as data on the hard drive. When executed, the operating system loads the program into main memory, or RAM. All running applications are given space in RAM by the operating system while they run. While running, the operating system monitors the application processes through a process table that describes the state of the process and where it resides in memory.

    Spawning Processes

    • Processes can spawn other processes intended to perform concurrent work during program execution. This "multiprocessing" allows programs to handle many different tasks at the same time. A program in Python, for example, can spawn a separate process using the "multiprocessing" library and its "Process" object, as in the following example:

      from multiprocessing import Process

      import os

      def hello():

      print('Hello')

      p = Process(target=hello)

      p.start() //starts child process "p"

    Processes Doing Work

    • A child process, given some task, will perform that task while the parent process performs its own task. In the following example, a Python program spawns a process, and both the parent process and the child process call the same method "os.getpid()", which returns the numerical id of the current process:

      def pId():

      print('I am Process: ', os.getpid())

      p = Process(target=pId)

      p.start()

      print('I am process: ', os.getpid())

      p.join() //ends the 'p' process

      The output of these two processes is as follows. Note that the parent "print" command with the lowercase "process" typically runs first.

      I am process: 57883

      I am Process: 57884

    Sharing Data Between Processes

    • Two processes can also share data between each other with a "Pipe" object that creates a connection between the two processes. Using these connection objects, a child process can send data to a parent process, enabling the parent process to manipulate or print the saved data. The following example displays the use of the Pipe object:

      def send(child):

      child.send([1, 2, 3]) //the child process sends the data when executing

      child.close()

      if __name__ == '__main__':

      parent, child = Pipe()

      p = Process(target=f, args=(child,))

      p.start()

      print parent.recv() //parent process receives data from child

      p.join

Source...
Subscribe to our newsletter
Sign up here to get the latest news, updates and special offers delivered directly to your inbox.
You can unsubscribe at any time

Leave A Reply

Your email address will not be published.