Python note 9-multithreaded threading blocking (join) and Daemon threads (Setdaemon)

Source: Internet
Author: User

Objective

Today Xiao Yoyo please xiaoming and Xiaowang eat hot pot, after eating hotpot will have the following three kinds of scenes:

    • Scene One: Small series (master) first Ate, xiaoming (guest) and Xiaowang (guest) has not eaten, this scene will lead to the checkout of the people go first, the remaining two small partners dumbfounded ...

    • Scene Two: Small series (main) first ate, xiaoming and xiaowang have not eaten full, together checkout leave.

    • Scene Three: Small series (master) first wait for xiaoming and Xiaowang eat full, small series finally checkout together leave.

Main thread and child thread

Scenario One: The main thread is over, the child thread is still running

1. We refer to Thread1.start () and Thread2.start () as two sub-threads, and the code that is written outside is the main thread.

#Coding=utf-8ImportThreadingImport TimedefChihuoguo (people):Print("%s Small hot pot Partner-Lamb:%s"%(Time.ctime (), people)) Time.sleep (1)    Print("%s Small pot-eating partner-Fish ball:%s"%(Time.ctime (), people))classMyThread (Threading. Thread):#inherits the parent class threading. Thread    def __init__(self, people, name):" "rewrite threading. Thread initialization Content" "Threading. Thread.__init__(self) self.threadname=name Self.people=peopledefRun (self):#write the code you want to execute into the run function. The thread runs the run function directly after it is created        " "overriding the Run method" "        Print("Start Thread:"+self.threadname) Chihuoguo (self.people)#Perform Tasks        Print("QQ Exchange Group: 226296743")        Print("End Thread:"+self.name)Print("Yoyo Please small partners to start eating hotpot:!!! ")#Create a new threadThread1 = MyThread ("xiaoming","Thread-1") Thread2= MyThread ("Xiaowang","Thread-2")#Open ThreadThread1.start () Thread2.start () Time.sleep (0.1)Print("exit main thread: Eat hotpot end, checkout leave")

2. Operation Result:

Daemon Thread Setdaemon ()

Scenario Two: The main thread is finished, and the child thread must also follow the end

1. In the main thread, the child threads Thread1 and Thread2 are created, and the Thread.setdaemon () is called in the main thread, this means that the main thread is set as the daemon thread, and if the main thread execution is finished, the pipe thread is not finished. and the main thread exits.
(Knocking the blackboard: must be set before the start () method call, if not set to the daemon thread, the program will be indefinitely suspended. )

2. A thread has a Boolean property called Daemon. Indicates whether the thread is a daemon thread and defaults to No. The program exits when all threads in the program are daemon threads. The program does not exit as long as there is a non-daemon thread.
The main thread is a non-daemon thread.

3.setDaemon (True) This method will take effect if the parameter is set to True

#Coding=utf-8ImportThreadingImport TimedefChihuoguo (people):Print("%s Small hot pot Partner-Lamb:%s"%(Time.ctime (), people)) Time.sleep (1)    Print("%s Small pot-eating partner-Fish ball:%s"%(Time.ctime (), people))classMyThread (Threading. Thread):#inherits the parent class threading. Thread    def __init__(self, people, name):" "rewrite threading. Thread initialization Content" "Threading. Thread.__init__(self) self.threadname=name Self.people=peopledefRun (self):#write the code you want to execute into the run function. The thread runs the run function directly after it is created        " "overriding the Run method" "        Print("Start Thread:"+self.threadname) Chihuoguo (self.people)#Perform Tasks        Print("QQ Exchange Group: 226296743")        Print("End Thread:"+self.name)Print("Yoyo Please small partners to start eating hotpot:!!! ")#Create a new threadThread1 = MyThread ("xiaoming","Thread-1") Thread2= MyThread ("Xiaowang","Thread-2")#Daemon Thread Setdaemon (True)Thread1.setdaemon (True)#must be before startThread2.setdaemon (True)#Open ThreadThread1.start () Thread2.start () Time.sleep (0.1)Print("exit main thread: Eat hotpot end, checkout leave")

4. Operation Result:

Block main thread Join (timeout)

1. If you want the main thread to wait for the child thread to end and then run it, you need to use Join (), which is after start (as opposed to Setdaemon)

2.join (Timeout) This method has a timeout parameter, which is set by the line blocks until those.

#Coding=utf-8ImportThreadingImport TimedefChihuoguo (people):Print("%s Small hot pot Partner-Lamb:%s"%(Time.ctime (), people)) Time.sleep (1)    Print("%s Small pot-eating partner-Fish ball:%s"%(Time.ctime (), people))classMyThread (Threading. Thread):#inherits the parent class threading. Thread    def __init__(self, people, name):" "rewrite threading. Thread initialization Content" "Threading. Thread.__init__(self) self.threadname=name Self.people=peopledefRun (self):#write the code you want to execute into the run function. The thread runs the run function directly after it is created        " "overriding the Run method" "        Print("Start Thread:"+self.threadname) Chihuoguo (self.people)#Perform Tasks        Print("QQ Exchange Group: 226296743")        Print("End Thread:"+self.name)Print("Yoyo Please small partners to start eating hotpot:!!! ")#Create a new threadThread1 = MyThread ("xiaoming","Thread-1") Thread2= MyThread ("Xiaowang","Thread-2")#Open ThreadThread1.start () Thread2.start ( )#block main thread, wait for child thread to endThread1.join () thread2.join () Time.sleep (0.1)Print("exit main thread: Eat hotpot end, checkout leave")

Operation Result:

Reference code:
#Coding=utf-8ImportThreadingImport TimedefChihuoguo (people):Print("%s Small hot pot Partner-Lamb:%s"%(Time.ctime (), people)) Time.sleep (1)    Print("%s Small pot-eating partner-Fish ball:%s"%(Time.ctime (), people))classMyThread (Threading. Thread):#inherits the parent class threading. Thread    def __init__(self, people, name):" "rewrite threading. Thread initialization Content" "Threading. Thread.__init__(self) self.threadname=name Self.people=peopledefRun (self):#write the code you want to execute into the run function. The thread runs the run function directly after it is created        " "overriding the Run method" "        Print("Start Thread:"+self.threadname) Chihuoguo (self.people)#Perform Tasks        Print("QQ Exchange Group: 226296743")        Print("End Thread:"+self.name)Print("Yoyo Please small partners to start eating hotpot:!!! ")#set up thread groupsThreads = []#Create a new threadThread1 = MyThread ("xiaoming","Thread-1") Thread2= MyThread ("Xiaowang","Thread-2")#add to Thread groupthreads.append (thread1) threads.append (thread2)#Open Thread forThreadinchThreads:thread.start ()#block main thread, wait for child thread to end forThreadinchThreads:thread.join () time.sleep (0.1)Print("exit main thread: Eat hotpot end, checkout leave")

Python note 9-multithreaded threading blocking (join) and Daemon threads (Setdaemon)

Related Article

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.