Concurrent Programming (daemon)

Source: Internet
Author: User
Tags terminates

A daemon process

The main process creates the child process and then sets the process to guard its own process

There are two points to emphasize about Daemons:

One: The daemon terminates after the execution of the main process code is completed

Second: The daemon can no longer open the child process, or throw an exception: Assertionerror:daemonic processes is not allowed to has children

If we have two tasks need to execute concurrently, then open a main process and a child process to execute separately is OK, if the child process of the task after the end of the main process is not necessary to exist, then the child process should be set to the daemon before opening. The daemon terminates after the main process code runs

#!/usr/bin/env python#-*-coding:utf-8-*- fromMultiprocessingImportProcessImport TimedefTask (name):Print('%s is piaoing'%name) Time.sleep (3)    Print('%s is Piao end'%name)if __name__=='__main__': P=process (target=task,args= ('Xiaojiu',)) P.daemon=true#be sure to set up before P.start (), set p to daemon, prevent p from creating child processes, and the parent process Code execution ends, p terminates the runP.start ()Print('Master')#as soon as the terminal prints out the line, the daemon p will end up.#OutputMain

Two exercises

Think about what might happen with the following code execution results? Why?

from multiprocessing import Processimport timedef foo():    print(123)    time.sleep(1)    print("end123")def bar():    print(456)    time.sleep(3)    print("end456")if __name__ == ‘__main__‘:    p1=Process(target=foo)    p2=Process(target=bar)    p1.daemon=True    p1.start()    p2.start()    print("main-------")

#输出

Main-------
456
end456

Because the main process is dead, P1 is dead,

Concurrent Programming (daemon)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.