Daemon processes
are low priority processes, which are mainly used for background processing.
How to make a process as daemon process?
By setting
daemon property to True, you can make a process as daemon process.
from multiprocessing import Process import multiprocessing def print_data(): name = multiprocessing.current_process().name id = multiprocessing.current_process().pid print(name, id) print("Is deamon ", multiprocessing.current_process().daemon) if __name__=="__main__": proc1 = Process(name='process1', target=print_data) proc1.daemon=True proc1.start() proc1.join() print("Finished")
Output
process1 31619 Is deamon True Finished
Python program
closes its execution, when no other non-daemon process/thread is alive.
from multiprocessing import Process import multiprocessing import time def print_data(): name = multiprocessing.current_process().name id = multiprocessing.current_process().pid print(name, id) time.sleep(3) print("Is deamon ", multiprocessing.current_process().daemon) if __name__=="__main__": proc1 = Process(name='process1', target=print_data) proc1.daemon=True proc1.start() time.sleep(1) print("Finished")
Output
process1 31675 Finished
Observe the
output, program terminated without printing second print statement of
print_data() method. To make daemon process finish execution, you should call
join method.
from multiprocessing import Process import multiprocessing import time def print_data(): name = multiprocessing.current_process().name id = multiprocessing.current_process().pid print(name, id) time.sleep(3) print("Is deamon ", multiprocessing.current_process().daemon) if __name__=="__main__": proc1 = Process(name='process1', target=print_data) proc1.daemon=True proc1.start() proc1.join() print("Finished")
Output
process1 31690 Is deamon True Finished
No comments:
Post a Comment