How to do it...

In the following example, we implement a target function, namely foo, which displays the digits from 0 to 4 if the child process is in the background; otherwise, it prints the digits from 5 to 9:

  1. Let's import the relevant libraries:
import multiprocessing
import time
  1. Then, we define the foo() function. As previously specified, the printed digits depend on the value of the name parameter:
def foo():
name = multiprocessing.current_process().name
print ("Starting %s " %name)
if name == 'background_process':
for i in range(0,5):
print('---> %d ' %i)
time.sleep(1)
else:
for i in range(5,10):
print('---> %d ' %i)
time.sleep(1)
print ("Exiting %s " %name)
  1. Finally, we define the following processes: background_process and NO_background_process. Notice that the daemon parameter is set for the two processes:
if __name__ == '__main__':
background_process = multiprocessing.Process
(name='background_process',
target=foo)
background_process.daemon = True

NO_background_process = multiprocessing.Process
(name='NO_background_process',
target=foo)

NO_background_process.daemon = False

background_process.start()
NO_background_process.start()
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.67.251